導航:首頁 > 音樂推薦 > java寫一個音樂播放器

java寫一個音樂播放器

發布時間:2021-03-13 19:10:56

A. java怎麼編寫一個簡單的音樂播放器

首先要在環境電腦中安裝下環境,才能引入javax.sound.sampled.*這個包,一下是用過的代碼
package TheMusic;
import java.io.*;

import javax.sound.sampled.*;

public class Music {

public static void main(String[] args) {

// TODO Auto-generated method stub

//修改你的音樂文件路徑就OK了

AePlayWave apw=new AePlayWave("突然好想你.wav");

apw.start();

}

}

在程序中實例化這個類,啟動線程,實例化的時候參照Test修改路徑就OK播放聲音的類
Java代碼

public class AePlayWave extends Thread {

private String filename;

public AePlayWave(String wavfile) {

filename = wavfile;

}

public void run() {

File soundFile = new File(filename);

AudioInputStream audioInputStream = null;

try {

audioInputStream = AudioSystem.getAudioInputStream(soundFile);

} catch (Exception e1) {

e1.printStackTrace();

return;

}

AudioFormat format = audioInputStream.getFormat();

SourceDataLine auline = null;

DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

try {

auline = (SourceDataLine) AudioSystem.getLine(info);

auline.open(format);

} catch (Exception e) {

e.printStackTrace();

return;

}

auline.start();

int nBytesRead = 0;

byte[] abData = new byte[512];

try {

while (nBytesRead != -1) {

nBytesRead = audioInputStream.read(abData, 0, abData.length);

if (nBytesRead >= 0)

auline.write(abData, 0, nBytesRead);

}

} catch (IOException e) {

e.printStackTrace();

return;

} finally {

auline.drain();

auline.close();

}

}

}

B. 有沒有高手給寫一個JAVA音樂播放器

以前寫的..博客裡面還有專很多種屬

http://hi..com/282919088/blog/item/e439ee0359ed058fd53f7c10.html

C. 如何用Java來編寫一個音樂播放器

首先要在環境電腦中安裝下JMF環境,才能引入javax.sound.sampled.*這個包,一下是用過的代碼
package TheMusic;
import java.io.*;

import javax.sound.sampled.*;

public class Music {

public static void main(String[] args) {

// TODO Auto-generated method stub

//修改你的音樂文件路徑就OK了

AePlayWave apw=new AePlayWave("突然好想你.wav");

apw.start();

}

}

在程序中實例化這個類,啟動線程,實例化的時候參照Test修改路徑就OK播放聲音的類
Java代碼

public class AePlayWave extends Thread {

private String filename;

public AePlayWave(String wavfile) {

filename = wavfile;

}

public void run() {

File soundFile = new File(filename);

AudioInputStream audioInputStream = null;

try {

audioInputStream = AudioSystem.getAudioInputStream(soundFile);

} catch (Exception e1) {

e1.printStackTrace();

return;

}

AudioFormat format = audioInputStream.getFormat();

SourceDataLine auline = null;

DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

try {

auline = (SourceDataLine) AudioSystem.getLine(info);

auline.open(format);

} catch (Exception e) {

e.printStackTrace();

return;

}

auline.start();

int nBytesRead = 0;

byte[] abData = new byte[512];

try {

while (nBytesRead != -1) {

nBytesRead = audioInputStream.read(abData, 0, abData.length);

if (nBytesRead >= 0)

auline.write(abData, 0, nBytesRead);

}

} catch (IOException e) {

e.printStackTrace();

return;

} finally {

auline.drain();

auline.close();

}

}

}

D. 如何用java做一個音樂播放器

<object id="player" height="300" width="300" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
<param NAME="AutoStart" VALUE="-1">
<!--是否自動播放-->
<param NAME="Balance" VALUE="0">
<!--調整左右聲道平衡,同上面舊播放器代碼-->
<param name="enabled" value="-1">
<!--播放器是否可人為控制-->
<param NAME="EnableContextMenu" VALUE="-1">
<!--是否啟用上下文菜單-->
<param NAME="url" value="song/onceLoveYou.mp3">
<!--播放的文件地址-->
<param NAME="PlayCount" VALUE="3">
<!--播放次數控制,為整數-->
<param name="rate" value="1">
<!--播放速率控制,1為正常,允許小數,1.0-2.0-->
<param name="currentPosition" value="0">
<!--控制項設置:當前位置-->
<param name="currentMarker" value="0">
<!--控制項設置:當前標記-->
<param name="defaultFrame" value="">
<!--顯示默認框架-->
<param name="invokeURLs" value="0">
<!--腳本命令設置:是否調用URL-->
<param name="baseURL" value="">
<!--腳本命令設置:被調用的URL-->
<param name="stretchToFit" value="0">
<!--是否按比例伸展-->
<param name="volume" value="50">
<!--默認聲音大小0%-100%,50則為50%-->
<param name="mute" value="0">
<!--是否靜音-->
<param name="uiMode" value="mini">
<!--播放器顯示模式:Full顯示全部;mini最簡化;None不顯示播放控制,只顯示視頻窗口;invisible全部不顯示-->
<param name="windowlessVideo" value="0">
<!--如果是0可以允許全屏,否則只能在窗口中查看-->
<param name="fullScreen" value="0">
<!--開始播放是否自動全屏-->
<param name="enableErrorDialogs" value="-1">
<!--是否啟用錯誤提示報告-->
<param name="SAMIStyle" value>
<!--SAMI樣式-->
<param name="SAMILang" value>
<!--SAMI語言-->
<param name="SAMIFilename" value>
<!--字幕ID-->
</object>
希望對你有所幫助

E. 用java編寫MP3播放器

作業其實還是自己寫的好。要用到JMF包啊,到網上下載一個JMF包,照著說明安裝上。
以下是我寫的一個很簡單的播放器,只能播放mp3,mpeg,mpg,wav等簡單的格式。
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.MediaLocator;
import javax.media.RealizeCompleteEvent;
import javax.media.bean.playerbean.MediaPlayer;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JList;
import java.awt.BorderLayout;
import javax.swing.JSplitPane;
import java.awt.Component;
import java.util.Vector;

public class JMF_T extends JFrame implements ControllerListener, ActionListener {
MediaPlayer Player;

private String filename = "";

private static final long serialVersionUID = 1L;

private Vector vct = new Vector(); // @jve:decl-index=0:

private JPanel jContentPane = null;

private JSplitPane jSplitPane = null;

private JPanel playPanel = null;

private JList jList = null;

private JSplitPane getJSplitPane() {
if (jSplitPane == null) {
jSplitPane = new JSplitPane();
jSplitPane.setDividerSize(5);
jSplitPane.setResizeWeight(0.8);
jSplitPane.setRightComponent(getJList());
jSplitPane.setLeftComponent(getPlayPanel());
}
return jSplitPane;
}

private JPanel getPlayPanel() {
if (playPanel == null) {
playPanel = new JPanel();
playPanel.setLayout(new BorderLayout());
}
return playPanel;
}

private JList getJList() {
if (jList == null) {
jList = new JList();
jList.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
// TODO Auto-generated Event stub mouseClicked()
if (e.getClickCount() == 1) {
String str = (String) jList.getSelectedValue();
if (str == null) {
return;
}
filename = str;
System.out.println(str);
}
if (e.getClickCount() == 2) {
String str = (String) jList.getSelectedValue();
if (str == null) {
return;
}
filename = str;
play();
}
}
});
}
return jList;
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JMF_T thisClass = new JMF_T();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
});
}

public JMF_T() {
initialize();
}

private void OpenFile() {
FileDialog fd = new FileDialog(this, "Choose Video", FileDialog.LOAD);
fd.setVisible(true);
filename = fd.getDirectory() + fd.getFile();
System.out.println(filename);
if (filename.equals("")) {
return;
} else if (filename.equals("nullnull")) {
return;
}
boolean j = false;
for (int i = 0; i < vct.size(); i++) {
if (vct.get(i).toString().equals(filename)) {
j = true;
break;
}
}
if (j == false) {
vct.add(filename);
jList.setListData(vct);
}
}

private void stop() {
if (Player != null) {
Player.stop();
Player.deallocate();
}
}

private void play() {
try {
if (filename.equals("")) {
return;
}
if (Player == null) {
Player = new MediaPlayer();
} else {
closePreviosPlayer();
}
Player.setMediaLocator(new MediaLocator("file:///" + filename));
Player.addControllerListener(this);
Player.realize();
Player.start();
} catch (Exception e) {

}
}

public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand().toString();
if (action.equals("Open")) {
OpenFile();
}
if (action.equals("Play")) {
play();
}
if (action.equals("Stop")) {
stop();
}
if (action.equals("Exit")) {
dispose();
System.exit(0);
}
}

private void initialize() {
this.setSize(500, 350);
setLocation(300, 100);
this.setContentPane(getJContentPane());
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
MenuBar mb = new MenuBar();
setMenuBar(mb);
Menu fileMenu = new Menu("File");
Menu actMenu = new Menu("Action");
mb.add(fileMenu);
mb.add(actMenu);
MenuItem itemOpen = new MenuItem("Open");
itemOpen.addActionListener(this);
fileMenu.add(itemOpen);
fileMenu.addSeparator();

MenuItem itemPlay = new MenuItem("Play");
itemPlay.addActionListener(this);
actMenu.add(itemPlay);
actMenu.addSeparator();

MenuItem itemStop = new MenuItem("Stop");
itemStop.addActionListener(this);
actMenu.add(itemStop);

MenuItem itemExit = new MenuItem("Exit");
itemExit.addActionListener(this);
fileMenu.add(itemExit);

this.validate();
this.setVisible(true);
}

private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(new BorderLayout());
jContentPane.add(getJSplitPane(), BorderLayout.CENTER);
}
return jContentPane;
}

private void closePreviosPlayer() {
if (Player == null)
return;
Player.stop();
Player.deallocate(); // 停止播放並且重新裝載DateSource
Component visual = Player.getVisualComponent();
Component control = Player.getControlPanelComponent();
if (visual != null) {
playPanel.remove(visual);
}
if (control != null) {
playPanel.remove(control);
}
}

public synchronized void controllerUpdate(ControllerEvent event) {
if (event instanceof RealizeCompleteEvent) {
Component comp;
if ((comp = Player.getControlPanelComponent()) != null) {
playPanel.add("South", comp);
} else {
closePreviosPlayer();
}
if ((comp = Player.getVisualComponent()) != null) {
playPanel.add("Center", comp);
}
validate();
}

}
}

F. java,我在寫一個音樂播放器(只播放本地音樂),

請先確定您的音樂鏈接是否有效。操作方法:將您貼到音樂盒中的音樂鏈專接,粘貼到屬IE瀏覽器的地址欄中打開,查看是否能夠收聽;2請確定您添加的音樂鏈接最後三個字母為mp3或wma,如果只是由您自己簡單將網頁名稱修改後粘貼的鏈接,仍然是無效的。 並注意最後面的地址不要多復制了一個空格。3在音樂收藏中,點擊您音樂盒中不能收聽音樂的編輯按鈕,核對您所貼到音樂盒中的鏈接是否與您在網頁上找到的一致。4如果您在音樂收藏中點擊單首歌曲可以播放,但添加到播放列表中無法播放,請將此歌曲在播放列表中刪除,再添加一次。為什麼聽不到自己空間里的音樂?請您核實瀏覽器是否安裝了網頁助手之類的插件。該插件若是設置了 禁止播放網頁音樂則是無法播放的,請將該屏蔽功能關閉即可。其次請安裝 MediaPlayer 播放軟體後嘗試!且請在「音樂盒」播放列表中注意「更新播放列表」。請您注意測試該歌曲的鏈接是否存在不穩定情況,建議您可以更換其他鏈接嘗試。或者您也可以直接使用音樂庫中的歌曲。其次請在「音樂盒」播放列表中注意「更新播放列表」。

G. 請問誰能提供一個用JAVA編寫的簡單的音頻播放器

//以下引入包 import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.applet.*; public class regit extends JApplet implements ActionListener,ItemListener//介面 { String s=null; //對象的聲明 JLabel labelname,labelpass,labelsxe,labeladdress,labelmail,labelphone;//標簽 JTextField textname,textaddress,textmail,textphone;//文本框 JRadioButton r1,r2;//單選按紐 ButtonGroup bg;//組 JPasswordField textpass;//密碼域 JButton buttonregit,buttonreset;//注冊按紐 重寫按紐 JPanel p;//面板 String sex;//定義性別字元串 URL url;//統一資源定位 BufferedWriter out1,out2;//流 BufferedReader in; //布局方式 GridBagLayout gbl; GridBagConstraints gc; AppletContext co;//介面 //初始化 public void init() { //new 對象 labelname=new JLabel("用 戶 名:"); labelpass=new JLabel("用戶密碼:"); labelsxe=new JLabel("性別:"); labeladdress=new JLabel("地址:"); labelmail=new JLabel("電子郵件:"); labelphone=new JLabel("聯系電話:"); textname=new JTextField(15); textname.setForeground(Color.red); textname.setToolTipText("請在這輸入你的用戶名"); textaddress=new JTextField(15);textaddress.setForeground(Color.red); textaddress.setToolTipText("請在這輸入你的地址"); textmail=new JTextField(15); textmail.setForeground(Color.red); textmail.setToolTipText("請在這里輸入你的E-mail地址"); textphone=new JTextField(15); textphone.setForeground(Color.red); textphone.setToolTipText("請在這輸入你的電話號碼"); r1=new JRadioButton("男"); r1.setBackground(new Color(47,177,210));//設置顏色 r2=new JRadioButton("女"); r2.setBackground(new Color(47,177,210));//設置顏色 bg=new ButtonGroup(); bg.add(r1);bg.add(r2);//加入組,實現單選 textpass=new JPasswordField(15); textpass.setToolTipText("在這里輸入密碼"); textpass.setForeground(Color.red); buttonregit=new JButton("注冊"); buttonregit.setBackground(new Color(47,177,210));//設置顏色 buttonregit.setToolTipText("點擊按紐完成注冊"); buttonreset=new JButton("填寫"); buttonreset.setBackground(new Color(47,177,210));//設置顏色 buttonreset.setToolTipText("點擊按紐刷新重寫"); gbl=new GridBagLayout(); /////////////////////////////////////// gc=new GridBagConstraints(); //////採用GridBagLayout布局方式//////// p=new JPanel(); p.setLayout(gbl); p.setBackground(new Color(47,177,210)); this.getContentPane().add(p);//加入面板 gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=2; gc.gridy=2; gbl.setConstraints(labelname,gc); p.add(labelname); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=4; gc.gridy=2; gbl.setConstraints(textname,gc); p.add(textname); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=2; gc.gridy=4; gbl.setConstraints(labelpass,gc); p.add(labelpass); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=4; gc.gridy=4; gbl.setConstraints(textpass,gc); p.add(textpass); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=2; gc.gridy=6; gbl.setConstraints(labelsxe,gc); p.add(labelsxe); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=4; gc.gridy=6; gbl.setConstraints(r1,gc); p.add(r1); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=5; gc.gridy=6; gbl.setConstraints(r2,gc); p.add(r2); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=2; gc.gridy=8; gbl.setConstraints(labeladdress,gc); p.add(labeladdress); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=4; gc.gridy=8; gbl.setConstraints(textaddress,gc); p.add(textaddress); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=2; gc.gridy=10; gbl.setConstraints(labelmail,gc); p.add(labelmail); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=4; gc.gridy=10; gbl.setConstraints(textmail,gc); p.add(textmail); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=2; gc.gridy=12; gbl.setConstraints(labelphone,gc); p.add(labelphone); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=4; gc.gridy=12; gbl.setConstraints(textphone,gc); p.add(textphone); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=2; gc.gridy=16; gbl.setConstraints(buttonregit,gc); p.add(buttonregit); gc.anchor=GridBagConstraints.NORTHWEST; gc.gridx=4; gc.gridy=16; gbl.setConstraints(buttonreset,gc); p.add(buttonreset); ///////////////////////////////////////////// co=this.getAppletContext(); ///////////////////////////////////////////// buttonregit.addActionListener(this);//按紐事件的監聽 buttonreset.addActionListener(this);//按紐事件的監聽 r1.addItemListener(this);//選擇事件的監聽 r2.addItemListener(this);//選擇事件的監聽 textphone.addActionListener(this); } public void actionPerformed(ActionEvent e) { //注冊按紐事件 if(e.getSource()==buttonregit) { String s1=textname.getText(); //////////////////// String s2=new String(textpass.getPassword());//////////////////// String s3=textaddress.getText(); // 定義字元串 // String s4=textmail.getText(); //////////////////// String s5=textphone.getText(); //////////////////// //判斷注冊資料 信息 是否為空 if(s1.length()==0 || s2.length()==0 ||s3.length()==0 ||s4.length()==0 ||s5.length()==0) { int error=JOptionPane.INFORMATION_MESSAGE; JOptionPane.showMessageDialog(null,"資料不能為空,請重新注冊!","【溫馨提示】",error); return;//彈出對話框並返回 } try//寫入到txt文件 { in=new BufferedReader(new FileReader("d:\\迷離視線聊天室\\password.txt")); } catch(Exception ee){} String ss=s1; try { while((s=in.readLine())!=null) { if(s.startsWith(ss)) { JOptionPane.showMessageDialog(null,"用戶名已經存在,請更換名字!"); textname.setText("");//設置為空,重新輸入 textpass.setText(""); textaddress.setText(""); textmail.setText(""); textphone.setText(""); return; } } } catch(Exception ee){} ///////////////////////////以上代碼判斷是否有同名 { try { out1=new BufferedWriter(new FileWriter("d:\\迷離視線聊天室\\password.txt",true)); out2=new BufferedWriter(new FileWriter("d:\\迷離視線聊天室\\message.txt",true)); }//創建文件 catch(Exception ee) {} try { out1.write(s1+"#"+s2);//寫 out1.newLine(); out2.write("用戶名:"+s1); out2.newLine(); out2.write("密碼:"+s2); out2.newLine(); out2.write("性別:"+sex); out2.newLine(); out2.write("地址:"+s3); out2.newLine(); out2.write("電子郵件:"+s4); out2.newLine(); out2.write("電話:"+s5); out2.newLine(); out1.flush(); out2.flush();//清理緩沖 out1.close(); out2.close(); } catch(Exception ee) {} JOptionPane.showMessageDialog(null,"注冊成功!"); try { String qss="http://localhost/chatroom/chatjiemian.htm"; url=new url(/qss);//連接上網址 co.showDocument(url); } catch(Exception exx) {} } } //////////////////////以下為回車事件 if(e.getSource()==textphone) { String s1=textname.getText(); //////////////////// String s2=new String(textpass.getPassword());//////////////////// String s3=textaddress.getText(); // 定義字元串 // String s4=textmail.getText(); //////////////////// String s5=textphone.getText(); //////////////////// //判斷注冊資料 信息 是否為空 if(s1.length()==0 || s2.length()==0 ||s3.length()==0 ||s4.length()==0 ||s5.length()==0) { int error=JOptionPane.INFORMATION_MESSAGE; JOptionPane.showMessageDialog(null,"資料不能為空,請重新注冊!","【溫馨提示】",error); return;//彈出對話框並返回 } try//寫入到txt文件 { in=new BufferedReader(new FileReader("d:\\迷離視線聊天室\\password.txt")); } catch(Exception ee){} String ss=s1; try { while((s=in.readLine())!=null) { if(s.startsWith(ss)) { JOptionPane.showMessageDialog(null,"用戶名已經存在,請更換名字!"); textname.setText("");//設置為空,重新輸入 textpass.setText(""); textaddress.setText(""); textmail.setText(""); textphone.setText(""); return; } } } catch(Exception ee){} ///////////////////////////以上代碼判斷是否有同名 { try { out1=new BufferedWriter(new FileWriter("d:\\迷離視線聊天室\\password.txt",true)); out2=new BufferedWriter(new FileWriter("d:\\迷離視線聊天室\\message.txt",true)); }//創建文件 catch(Exception ee) {} try { out1.write(s1+"#"+s2);//寫 out1.newLine(); out2.write("用戶名:"+s1+"密碼:"+s2+"性別:"+sex+"地址:"+s3+"電子郵件:"+s4+"電話:"+s5);//寫 out2.newLine(); out1.flush(); out2.flush();//清理緩沖 out1.close(); out2.close(); } catch(Exception ee) {} JOptionPane.showMessageDialog(null,"注冊成功!"); try { String qss="http://localhost/chatroom/chatjiemian.htm"; url=new url(/qss);//連接上網址 co.showDocument(url); } catch(Exception exx) {} } } if(e.getSource()==buttonreset)//刷新重寫事件 { textname.setText(""); textpass.setText(""); textaddress.setText(""); textmail.setText(""); textphone.setText(""); } } ////////////////////////////////////////// // public void itemStateChanged(ItemEvent ex) { if(ex.getSource()==r1) { sex=new String("男"); } else if(ex.getSource()==r2) { sex=new String("女"); } } }

H. java大神求解啊,如何用java編寫一個音樂播放器,然後播放器裡面的歌可以順序播放的。

參考代碼如下
首先下載播放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;// 播放線程狀態

String filepath;// 播放文件目錄
String filename;// 播放文件名稱
AudioInputStream audioInputStream;// 文件流
AudioFormat audioFormat;// 文件格式
SourceDataLine sourceDataLine;// 輸出設備

List list;// 文件列表
Label labelfilepath;//播放目錄顯示標簽
Label labelfilename;//播放文件顯示標簽

public MusicPlayer() {
// 設置窗體屬性
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");

// 注冊窗體關閉事件
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();
// 轉換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);
}

// 打開輸出設備
DataLine.Info dataLineInfo = new DataLine.Info(
SourceDataLine.class, audioFormat,
AudioSystem.NOT_SPECIFIED);
sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();

// 創建獨立線程進行播放
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;
// 讀取數據到緩存數據
while ((cnt = audioInputStream.read(tempBuffer, 0,
tempBuffer.length)) != -1) {
if (isStop)
break;
if (cnt > 0) {
// 寫入緩存數據
sourceDataLine.write(tempBuffer, 0, cnt);
}
}
// Block等待臨時數據被輸出為空
sourceDataLine.drain();
sourceDataLine.close();
hasStop = true;
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
}

public static void main(String args[]) {
new MusicPlayer();
}
}

閱讀全文

與java寫一個音樂播放器相關的資料

熱點內容
愛情圍牆歌詞 瀏覽:230
道奇酷威廣告背景音樂 瀏覽:106
比喻輕音樂之美的文字 瀏覽:542
小號音樂下載 瀏覽:578
歌曲專輯圖下載地址 瀏覽:867
財神駕到歌曲mp3下載 瀏覽:734
琴歌指彈海闊天空吉他譜 瀏覽:355
下載mp4格式的音樂 瀏覽:352
電腦聽音樂用什麼 瀏覽:512
最好酷狗音樂播放器 瀏覽:502
信樂團隊的假如簡譜 瀏覽:243
平安酷狗音樂 瀏覽:760
佳人輕撫桃花mp3下載 瀏覽:453
infinite網易雲音樂 瀏覽:844
歲月趙忠祥背景音樂 瀏覽:980
如何將電腦的歌體添加到蘋果音樂 瀏覽:672
fade鋼琴mp3 瀏覽:86
奔跑吧兄弟宋仲基背景音樂 瀏覽:806
成都彩虹小學音樂老師 瀏覽:496
鳳凰傳奇星光歌曲點評 瀏覽:930