import javax.media.*;
平山網(wǎng)站制作公司哪家好,找成都創(chuàng)新互聯(lián)!從網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站開發(fā)等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營(yíng)維護(hù)。成都創(chuàng)新互聯(lián)成立于2013年到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選成都創(chuàng)新互聯(lián)。
import java.awt.*;
import java.awt.event.*;
class MediaPlayer extends Frame implements ActionListener,
ControllerListener, ItemListener
{
Player player;
Component vc, cc;
boolean first = true, loop = false;
String currentDirectory;
MediaPlayer (String title)
{
super (title);
addWindowListener
(new WindowAdapter ()
{
public void windowClosing (WindowEvent e) {
// 用戶點(diǎn)擊窗口系統(tǒng)菜單的關(guān)閉按鈕
// 調(diào)用dispose以執(zhí)行windowClosed
dispose ();
} public void windowClosed (WindowEvent e) {
if (player != null) player.close ();
System.exit (0);
}
});
Menu m = new Menu ("文件");
MenuItem mi = new MenuItem ("打開");
mi.addActionListener (this);
m.add (mi);
m.addSeparator ();
CheckboxMenuItem cbmi = new CheckboxMenuItem ("循環(huán)", false);
cbmi.addItemListener (this);
m.add (cbmi);
m.addSeparator ();
mi = new MenuItem ("退出");
mi.addActionListener (this);
m.add (mi);
MenuBar mb = new MenuBar ();
mb.add (m);
setMenuBar (mb);
setSize (200, 200);
setVisible (true);
}
public void actionPerformed (ActionEvent e)
{
if (e.getActionCommand ().equals ("退出"))
{
// 調(diào)用dispose以便執(zhí)行windowClosed
dispose ();
return;
}
FileDialog fd = new FileDialog (this, "打開媒體文件",
FileDialog.LOAD);
fd.setDirectory (currentDirectory);
fd.show ();
// 如果用戶放棄選擇文件,則返回
if (fd.getFile () == null) return;
currentDirectory = fd.getDirectory ();
if (player != null)
player.close ();
try
{
player = Manager.createPlayer (new MediaLocator ("file:" + fd.getDirectory () + fd.getFile ()));
}
catch (java.io.IOException e2)
{
System.out.println (e2);
return;
}
catch (NoPlayerException e2)
{
System.out.println ("不能找到播放器.");
return;
}
if (player == null)
{
System.out.println ("無(wú)法創(chuàng)建播放器.");
return;
}
first = false;
setTitle (fd.getFile ());
player.addControllerListener (this);
player.prefetch ();
}
public void controllerUpdate (ControllerEvent e)
{
// 調(diào)用player.close()時(shí)ControllerClosedEvent事件出現(xiàn)。
// 如果存在視覺部件,則該部件應(yīng)該拆除(為一致起見,
// 我們對(duì)控制面板部件也執(zhí)行同樣的操作)
if (e instanceof ControllerClosedEvent)
{
if (vc != null)
{
remove (vc);
vc = null;
}
if (cc != null)
{
remove (cc);
cc = null;
}
return;
}
if (e instanceof EndOfMediaEvent)
{
if (loop)
{
player.setMediaTime (new Time (0));
player.start ();
}
return;
}
if (e instanceof PrefetchCompleteEvent)
{
player.start ();
return;
}
if (e instanceof RealizeCompleteEvent)
{
vc = player.getVisualComponent ();
if (vc != null)
add (vc);
cc = player.getControlPanelComponent ();
if (cc != null)
add (cc, BorderLayout.SOUTH);
pack ();
}
}
public void itemStateChanged (ItemEvent e)
{
loop = !loop;
}
public void paint (Graphics g)
{
if (first)
{
int w = getSize ().width;
int h = getSize ().height;
g.setColor (Color.blue);
g.fillRect (0, 0, w, h);
Font f = new Font ("DialogInput", Font.BOLD, 16);
g.setFont (f);
FontMetrics fm = g.getFontMetrics ();
int swidth = fm.stringWidth ("*** 歡迎 ***");
g.setColor (Color.white);
g.drawString ("*** 歡迎 ***",
(w - swidth) / 2,
(h + getInsets ().top) / 2);
}
// 調(diào)用超類Frame的paint()方法,該paint()方法將調(diào)用Frame包含的各個(gè)容器
// 和部件(包括控制面板部件)的paint()方法。
super.paint (g);
}
// 不執(zhí)行背景清除操作,以免控制面板部件閃爍
public void update (Graphics g)
{
paint (g);
}
public static void main (String [] args) {
new MediaPlayer ("媒體播放器1.0");
} }
// 你看看吧。。 必須下載 jmf包 如果不知道下載就問我吧
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.media.bean.playerbean.MediaPlayer; //必須下載 jmf 媒體播放包
public class player extends Applet implements ActionListener {
Button b1, b2;
MediaPlayer player;
public void init() {
player = new MediaPlayer();
setLayout(new FlowLayout());
try{
player.setMediaLocation("file:/F:\\音樂\\mp3\\黑白配.mp3");// file:/不能刪除 音頻文件路徑
} catch (Exception e) {
System.out.println("文件不存在");
}
b1 = new Button("播放");
b2 = new Button("停止");
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
setSize(200, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
player.start();
} else if (e.getSource() == b2) {
player.stop();
System.out.println(player.getMediaTime().getSeconds());
}
}
}
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.media.ControllerClosedEvent;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.PrefetchCompleteEvent;
import javax.media.RealizeCompleteEvent;
import javax.media.Time;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class JMFMediaPlayer extends JFrame implements ActionListener,
ControllerListener, ItemListener {
// JMF的播放器
Player player;
// 播放器的視頻組件和控制組件
Component vedioComponent;
Component controlComponent;
// 標(biāo)示是否是第一次打開播放器
boolean first = true;
// 標(biāo)示是否需要循環(huán)
boolean loop = false;
// 文件當(dāng)前目錄
String currentDirectory;
// 構(gòu)造方法
public JMFMediaPlayer(String title) {
super(title);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
// 用戶點(diǎn)擊窗口系統(tǒng)菜單的關(guān)閉按鈕
// 調(diào)用dispose以執(zhí)行windowClosed
dispose();
}
public void windowClosed(WindowEvent e){
if (player != null){
// 關(guān)閉JMF播放器對(duì)象
player.close();
}
System.exit(0);
}
});
// 創(chuàng)建播放器的菜單
JMenu fileMenu = new JMenu("文件");
JMenuItem openMemuItem = new JMenuItem("打開");
openMemuItem.addActionListener(this);
fileMenu.add(openMemuItem);
// 添加一個(gè)分割條
fileMenu.addSeparator();
// 創(chuàng)建一個(gè)復(fù)選框菜單項(xiàng)
JCheckBoxMenuItem loopMenuItem = new JCheckBoxMenuItem("循環(huán)", false);
loopMenuItem.addItemListener(this);
fileMenu.add(loopMenuItem);
fileMenu.addSeparator();
JMenuItem exitMemuItem = new JMenuItem("退出");
exitMemuItem.addActionListener(this);
fileMenu.add(exitMemuItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);
this.setSize(200, 200);
try {
// 設(shè)置界面的外觀,為系統(tǒng)外觀
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
e.printStackTrace();
}
this.setVisible(true);
}
/**
* 實(shí)現(xiàn)了ActionListener接口,處理組件的活動(dòng)事件
*/
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("退出")) {
// 調(diào)用dispose以便執(zhí)行windowClosed
dispose();
return;
}
FileDialog fileDialog = new FileDialog(this, "打開媒體文件", FileDialog.LOAD);
fileDialog.setDirectory(currentDirectory);
fileDialog.setVisible(true);
// 如果用戶放棄選擇文件,則返回
if (fileDialog.getFile() == null){
return;
}
currentDirectory = fileDialog.getDirectory();
if (player != null){
// 關(guān)閉已經(jīng)存在JMF播放器對(duì)象
player.close();
}
try {
// 創(chuàng)建一個(gè)打開選擇文件的播放器
player = Manager.createPlayer(new MediaLocator("file:"
+ fileDialog.getDirectory() + fileDialog.getFile()));
} catch (java.io.IOException e2) {
System.out.println(e2);
return;
} catch (NoPlayerException e2) {
System.out.println("不能找到播放器.");
return;
}
if (player == null) {
System.out.println("無(wú)法創(chuàng)建播放器.");
return;
}
first = false;
this.setTitle(fileDialog.getFile());
// 播放器的控制事件處理
player.addControllerListener(this);
// 預(yù)讀文件內(nèi)容
player.prefetch();
}
/**
* 實(shí)現(xiàn)ControllerListener接口的方法,處理播放器的控制事件
*/
public void controllerUpdate(ControllerEvent e) {
// 調(diào)用player.close()時(shí)ControllerClosedEvent事件出現(xiàn)。
// 如果存在視覺部件,則該部件應(yīng)該拆除(為一致起見,
// 我們對(duì)控制面板部件也執(zhí)行同樣的操作)
if (e instanceof ControllerClosedEvent) {
if (vedioComponent != null) {
this.getContentPane().remove(vedioComponent);
this.vedioComponent = null;
}
if (controlComponent != null) {
this.getContentPane().remove(controlComponent);
this.controlComponent = null;
}
return;
}
// 如果是媒體文件到達(dá)尾部事件
if (e instanceof EndOfMediaEvent) {
if (loop) {
// 如果允許循環(huán),則重新開始播放
player.setMediaTime(new Time(0));
player.start();
}
return;
}
// 如果是播放器預(yù)讀事件
if (e instanceof PrefetchCompleteEvent) {
// 啟動(dòng)播放器
player.start();
return;
}
// 如果是文件打開完全事件,則顯示視頻組件和控制器組件
if (e instanceof RealizeCompleteEvent) {
vedioComponent = player.getVisualComponent();
if (vedioComponent != null){
this.getContentPane().add(vedioComponent);
}
controlComponent = player.getControlPanelComponent();
if (controlComponent != null){
this.getContentPane().add(controlComponent, BorderLayout.SOUTH);
}
this.pack();
}
}
// 處理“循環(huán)”復(fù)選框菜單項(xiàng)的點(diǎn)擊事件
public void itemStateChanged(ItemEvent e) {
loop = !loop;
}
public static void main(String[] args){
new JMFMediaPlayer("JMF媒體播放器");
}
}
試試吧,我這里運(yùn)行正常
看看其它網(wǎng)友的答案:
首先下載播放mp3的包,比如mp3spi1.9.4.jar。在工程中添加這個(gè)包。
播放器演示代碼如下
package com.test.audio;
import java.io.File;
import java.awt.BorderLayout;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.List;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
public class MusicPlayer extends Frame {
/**
*
*/
private static final long serialVersionUID = -2605658046194599045L;
boolean isStop = true;// 控制播放線程
boolean hasStop = true;// 播放線程狀態(tài)
String filepath;// 播放文件目錄
String filename;// 播放文件名稱
AudioInputStream audioInputStream;// 文件流
AudioFormat audioFormat;// 文件格式
SourceDataLine sourceDataLine;// 輸出設(shè)備
List list;// 文件列表
Label labelfilepath;//播放目錄顯示標(biāo)簽
Label labelfilename;//播放文件顯示標(biāo)簽
public MusicPlayer() {
// 設(shè)置窗體屬性
setLayout(new BorderLayout());
setTitle("MP3 Music Player");
setSize(350, 370);
// 建立菜單欄
MenuBar menubar = new MenuBar();
Menu menufile = new Menu("File");
MenuItem menuopen = new MenuItem("Open", new MenuShortcut(KeyEvent.VK_O));
menufile.add(menuopen);
menufile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
open();
}
});
menubar.add(menufile);
setMenuBar(menubar);
// 文件列表
list = new List(10);
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// 雙擊時(shí)處理
if (e.getClickCount() == 2) {
// 播放選中的文件
filename = list.getSelectedItem();
play();
}
}
});
add(list, "Center");
// 信息顯示
Panel panel = new Panel(new GridLayout(2, 1));
labelfilepath = new Label("Dir:");
labelfilename = new Label("File:");
panel.add(labelfilepath);
panel.add(labelfilename);
add(panel, "North");
// 注冊(cè)窗體關(guān)閉事件
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setVisible(true);
}
// 打開
private void open() {
FileDialog dialog = new FileDialog(this, "Open", 0);
dialog.setVisible(true);
filepath = dialog.getDirectory();
if (filepath != null) {
labelfilepath.setText("Dir:" + filepath);
// 顯示文件列表
list.removeAll();
File filedir = new File(filepath);
File[] filelist = filedir.listFiles();
for (File file : filelist) {
String filename = file.getName().toLowerCase();
if (filename.endsWith(".mp3") || filename.endsWith(".wav")) {
list.add(filename);
}
}
}
}
// 播放
private void play() {
try {
isStop = true;// 停止播放線程
// 等待播放線程停止
System.out.print("Start:" + filename);
while (!hasStop) {
System.out.print(".");
try {
Thread.sleep(10);
} catch (Exception e) {
}
}
System.out.println("");
File file = new File(filepath + filename);
labelfilename.setText("Playing:" + filename);
// 取得文件輸入流
audioInputStream = AudioSystem.getAudioInputStream(file);
audioFormat = audioInputStream.getFormat();
// 轉(zhuǎn)換mp3文件編碼
if (audioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
audioFormat.getSampleRate(), 16, audioFormat
.getChannels(), audioFormat.getChannels() * 2,
audioFormat.getSampleRate(), false);
audioInputStream = AudioSystem.getAudioInputStream(audioFormat,
audioInputStream);
}
// 打開輸出設(shè)備
DataLine.Info dataLineInfo = new DataLine.Info(
SourceDataLine.class, audioFormat,
AudioSystem.NOT_SPECIFIED);
sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
// 創(chuàng)建獨(dú)立線程進(jìn)行播放
isStop = false;
Thread playThread = new Thread(new PlayThread());
playThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
class PlayThread extends Thread {
byte tempBuffer[] = new byte[320];
public void run() {
try {
int cnt;
hasStop = false;
// 讀取數(shù)據(jù)到緩存數(shù)據(jù)
while ((cnt = audioInputStream.read(tempBuffer, 0,
tempBuffer.length)) != -1) {
if (isStop)
break;
if (cnt 0) {
// 寫入緩存數(shù)據(jù)
sourceDataLine.write(tempBuffer, 0, cnt);
}
}
// Block等待臨時(shí)數(shù)據(jù)被輸出為空
sourceDataLine.drain();
sourceDataLine.close();
hasStop = true;
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
}
public static void main(String args[]) {
new MusicPlayer();
}
}
簡(jiǎn)單的實(shí)例,代碼如下,純粹JMF加載MP3并播放:
import javax.media.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PlayerMusic implements ControllerListener {// ControllerListener
// 控制事件
private Player player;
private boolean first, loop;
private String path;
private List mp3List;
private int mp3NO = 0;
PlayerMusic(List mp3List) {
this.mp3List = mp3List;
}
public void start() {
try {
player = Manager.createPlayer(new MediaLocator("file://" + mp3List.get(mp3NO)));
} catch (NoPlayerException ex) {
ex.printStackTrace();
System.out.println("不能播放文件");
return;
} catch (IOException ex) {
ex.printStackTrace();
return;
}
if (player == null) {
System.out.println("播放器為空");
return;
}
first = false;
player.addControllerListener(this);
// 提取媒體內(nèi)容
player.prefetch();
}
public void controllerUpdate(ControllerEvent e) {
// 當(dāng)媒體播放結(jié)束時(shí),循環(huán)播放
if (e instanceof EndOfMediaEvent) {
mp3NO++;
if(mp3NOthis.mp3List.size()){
this.start();
}
return;
}
// 當(dāng)預(yù)提取媒體的內(nèi)容結(jié)束
if (e instanceof PrefetchCompleteEvent) {
player.start();
return;
}
// 當(dāng)實(shí)例化后
if (e instanceof RealizeCompleteEvent) {
// pack(); //執(zhí)行pack()操作
return;
}
}
public static void main(String[] args) {
List mp3List = new ArrayList();
mp3List.add("d://a.mp3");
mp3List.add("d://b.mp3");
mp3List.add("d://c.mp3");
PlayerMusic pm = new PlayerMusic(mp3List);
pm.start();
}
}
本文名稱:音頻播放器java代碼,java編寫視頻播放器
文章位置:http://chinadenli.net/article0/hdocio.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、網(wǎng)站營(yíng)銷、品牌網(wǎng)站制作、定制網(wǎng)站、網(wǎng)頁(yè)設(shè)計(jì)公司、電子商務(wù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
網(wǎng)頁(yè)設(shè)計(jì)公司知識(shí)