62,614
社区成员
发帖
与我相关
我的任务
分享
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 {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音乐播放器");setSize(350, 370); //建立菜单栏MenuBar menubar = new MenuBar();Menu menufile = new Menu("文件");MenuItem menuopen = new MenuItem("打开", 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("播放目录:");labelfilename = new Label("播放文件:");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("播放目录:" + 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("开始播放:" + filename);while (!hasStop) {System.out.print(".");try {Thread.sleep(10);} catch (Exception e) {}}System.out.println("");File file = new File(filepath + filename);labelfilename.setText("播放文件:" + 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();}} public static void main(String args[]) {new MusicPlayer();}}
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);}}}
package com;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.media.CannotRealizeException;
import javax.media.Controller;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.Manager;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.Time;
/*******************************************************************************
* Subclass: MusicPlay
******************************************************************************/
public class MusicPlay implements Runnable {
private Time zeroTime = new Time(0);
private Player player;
private boolean turnOff = false;
private boolean isloop = false;
/***************************************************************************
* Function: MusicPlay Description: constructor, load the music file and get
* ready for play Called By: MultiMedia()
**************************************************************************/
// 实例化各个参数 filename 为文件名,可为绝对路径
public MusicPlay(String filename) {
File file = new File(filename);
try {
player = Manager.createRealizedPlayer(file.toURI().toURL());
player.addControllerListener(new ControllListener());
} catch (NoPlayerException e) {
e.printStackTrace();
} catch (CannotRealizeException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/***************************************************************************
* Function: isRunning Description: test if this music is playing Called By:
**************************************************************************/
public boolean isRunning() {
return player.getState() == Player.Started;
}
/***************************************************************************
* Function: play Description: play the music for once Called By:
* resumeAll()
**************************************************************************/
// 只播放一次
public void play() {
if (!turnOff)
player.start();
}
/***************************************************************************
* Function: replay Description: replay the music Called By: musics that
* will be played many times will invoke this methed
**************************************************************************/
// 再播放一次
public void replay() {
if (turnOff)
return;
if (player.getState() == Controller.Prefetched)
player.setMediaTime(zeroTime);
player.start();
}
/***************************************************************************
* Function: stop Description: stop this music Called By: stopAll() of upper
* class,suspendAll() of upper class,BackroundForMenuPanel,GameOverPanel
**************************************************************************/
public void stop() {
player.stop();
}
/***************************************************************************
* Function: close Description: dispose the music Called By: closeAll() of
* super class
**************************************************************************/
public void close() {
player.stop();
player.close();
}
/***************************************************************************
* Function: loop Description: make the music played repetitiously Called
* By: music that will repetitious play
**************************************************************************/
// 循环播放
public void loop() {
if (turnOff)
return;
isloop = true;
player.prefetch();
replay();
}
/***************************************************************************
* Function: run Description: trig this music Called By: Override method
**************************************************************************/
public void run() {
loop();
}
/***************************************************************************
* Subclass: ControllListener Description: listener for playing and
* implement playing repetitiously
**************************************************************************/
// 通过对播放进度的监听,实现循环播放
private class ControllListener implements ControllerListener {
public void controllerUpdate(ControllerEvent e) {
if (e instanceof EndOfMediaEvent) {
if (isloop) {
player.setMediaTime(new Time(0));
player.start();
}
}
}
}
public static void main(String[] args) {
MusicPlay mp = new MusicPlay("w.mp3");
mp.play();
}
}
String file="c:\\歌曲名.mp3";
Runtime.getRuntime().exec("cmd /c start " + file.replaceAll(" ", "\" \""));