簡單的實例,代碼如下,純粹JMF加載MP3并播放:
創(chuàng)新互聯(lián)是一家專業(yè)的成都網(wǎng)站建設(shè)公司,我們專注網(wǎng)站制作、成都網(wǎng)站設(shè)計、網(wǎng)絡(luò)營銷、企業(yè)網(wǎng)站建設(shè),買鏈接,一元廣告為企業(yè)客戶提供一站式建站解決方案,能帶給客戶新的互聯(lián)網(wǎng)理念。從網(wǎng)站結(jié)構(gòu)的規(guī)劃UI設(shè)計到用戶體驗提高,創(chuàng)新互聯(lián)力求做到盡善盡美。
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é)束時,循環(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)實例化后
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();
}
}
這個程序只要寫對了音樂文件的URL地址,例如:new URL("file:/C:/tmp/1/Windows Ding.wav");
就可以播放音樂,除了可以播放.wav格式的音樂,還可以播放.au格式的音樂。
另外,如果你不希望音樂循環(huán)播放,你可以去掉audio1.loop();這一語句。
import java.applet.AudioClip;
import java點虐 .MalformedURLException;
import java點虐 .URL;
import javax.swing.JFrame;
public class D extends JFrame{
D(){
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
URL codebase=null;
try {
codebase = new URL("file:/C:/tmp/1/Windows Ding.wav");
} catch (MalformedURLException e) {
e.printStackTrace();
}
AudioClip audio1=Applet.newAudioClip(codebase);
audio1.loop();
}
public static void main(String[] args) {
new D();
}
}
首先下載播放mp3的包,比如mp3spi1.9.4.jar。在工程中添加這個包。
播放器演示代碼如下
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;//播放目錄顯示標簽
Label?labelfilename;//播放文件顯示標簽
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)?{
//?雙擊時處理
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");
//?注冊窗體關(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)建獨立線程進行播放
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ù)據(jù)被輸出為空
sourceDataLine.drain();
sourceDataLine.close();
hasStop?=?true;
}?catch?(Exception?e)?{
e.printStackTrace();
System.exit(0);
}
}
}
public?static?void?main(String?args[])?{
new?MusicPlayer();
}
}