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();
}
}