【实例简介】有图形用户界面、能根据本地路径导入本地音乐,项目中含jmf相关 jar包下载
【实例截图】
【核心代码】
import java.io.*;
//import java.applet.AudioClip;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
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.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;//获得音频文件中包含的音频数据的格式。
import javax.sound.sampled.AudioInputStream;//通过转换提供的音频输入流,获得所指示格式的音频输入流。
import javax.sound.sampled.AudioSystem;
//import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JOptionPane;
//import com.sun.javafx.collections.MappingChange.Map;
//
//import javazoom.jl.decoder.Manager;
//import javazoom.jl.player.Player;
//import javax.media.*;
//
//import javax.media.bean.*;
//import javax.management.*;
//import javax.media.bean.playerbean.*;
//import java.time.*;
//这里是标记
@SuppressWarnings("unused")
public class SoundPlayerTest extends Frame{
private static final long serialVersionUID = 1L;
boolean isStop = true;// 控制播放线程
boolean hasStop = true;// 播放线程状态
String filepath;// 播放文件目录
String filename;// 播放文件名称
AudioInputStream audioInputStream;// 文件流
AudioFormat audioFormat;// 文件格式
SourceDataLine sourceDataLine;// 输出设备
List list;// 文件列表
Label labelfilepath;//播放目录显示标签
Label labelfilename;//播放文件显示标签
Button buttonNext,buttonLast,buttonStop,showlist;//上、下一首、停止按钮,保存当前当前打开文件列表的音乐
int songNum,num,i,f=0;
int judge=0;
//String F[]=new String[10];
public SoundPlayerTest() throws IOException {
// 设置窗体属性
setLayout(new BorderLayout());
setTitle("音月");
setSize(380,500);
// 建立菜单栏
MenuBar menubar = new MenuBar();
Menu menufile = new Menu("菜单");
MenuItem menuopen = new MenuItem("打开");
MenuItem itemExit=new MenuItem("退出");
menufile.add(menuopen);
menufile.addSeparator();
menufile.add(itemExit);
menuopen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
open();
} catch (IOException e1) {
// TODO Auto-generated catch block
//e1.printStackTrace();
}
}
});
itemExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menubar.add(menufile);
setMenuBar(menubar);
// 文件列表
list = new List();
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// 双击时处理
if (e.getClickCount() == 2) {
// 播放选中的文件
filename = list.getSelectedItem();
songNum=list.getSelectedIndex();
num=songNum;
// System.out.printf("位置%d\n",songNum);
play();
}
}
});
list.setBackground(Color.pink);
add(list, "Center");
// 信息显示
Panel panel = new Panel(new GridLayout(0, 1));
labelfilepath = new Label("正在播放:");
labelfilename = new Label("播放列表");
buttonLast=new Button("上一首");
buttonLast.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
songNum=list.getSelectedIndex();
if(songNum>0){
list.select(songNum-1);
filename = list.getItem(songNum-1);
num=songNum-1;
play();
}
}
});
//****************************************
buttonStop=new Button("停止");
buttonStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
isStop=true;
labelfilepath.setText("播放停止");
}
});
//
//****************************************
showlist=new Button("导入");
showlist.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//歌曲显示
list.removeAll();
String w = "音乐路径.txt";
BufferedReader in = null;
try {
in = new BufferedReader( new FileReader(w));
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
//e2.printStackTrace();
}
String nowid = null;
try {
nowid = in.readLine();
} catch (IOException e2) {
// TODO Auto-generated catch block
//e2.printStackTrace();
}
labelfilepath.setText(nowid);
while(nowid!=null)
{
//F[f]=nowid;
filepath=nowid;
if (filepath != null) {
labelfilepath.setText("音乐路径:" filepath);
File filedir = new File(filepath);
File[] filelist = filedir.listFiles();//过滤该路径所在文件是wav,MP3格式的文件并在面板中显示
for (File file : filelist) {
String filename = file.getName().toLowerCase();
if (filename.endsWith(".wav")||filename.endsWith(".mp3")) {
list.add(filename);
}
}
}
//f ;
try {
nowid=in.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
//e1.printStackTrace();
}
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
//e1.printStackTrace();
}
}
});
//*****************************************
buttonNext=new Button("下一首");
buttonNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
songNum=list.getSelectedIndex();
if((songNum 1)
list.select(songNum 1);
filename = list.getItem(songNum 1);
num=songNum 1;
play();
}
}
});
buttonNext.setBackground(Color.ORANGE);
buttonLast.setBackground(Color.GREEN);
buttonStop.setBackground(Color.GRAY);
showlist.setBackground(Color.blue);
list.setBackground(Color.white);
panel.add(labelfilepath);
panel.add(buttonLast);
panel.add(buttonStop);
panel.add(buttonNext);
panel.add(showlist);
panel.add(labelfilename);
add(panel, "North");
// 注册窗体关闭事件
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setVisible(true);
}
// 打开
private void open() throws IOException {
FileDialog dialog = new FileDialog(this, "Open", 0);
dialog.setVisible(true);
boolean m=true;
String w = "音乐路径.txt";
BufferedReader in=new BufferedReader( new FileReader(w));
String nowid=in.readLine();
filepath = dialog.getDirectory();//保存对话框的路径
while(nowid!=null)
{
if(nowid.equals(filepath))
{
JOptionPane.showMessageDialog(null, "该路径已保存!"); //弹出提示框
m=false;
break ;
}
nowid=in.readLine();
}
if(m){
RandomAccessFile randomFile = new RandomAccessFile(w, "rw");
long fileLength = randomFile.length(); //将写文件指针移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(filepath "\r\n");
randomFile.close();
}
if (filepath != null) {
labelfilepath.setText("音乐路径:" filepath);
String song;
song=filepath ".txt";
BufferedWriter out=new BufferedWriter( new FileWriter(song));
// System.out.println("新建成功标记");
// 显示文件列表
File filedir = new File(filepath);
File[] filelist = filedir.listFiles();//过滤该路径所在文件是wav,MP3格式的文件并在面板中显示
for (File file : filelist) {
String filename = file.getName().toLowerCase();
if (filename.endsWith(".wav")||filename.endsWith(".mp3")) {
list.add(filename);
out.write(filename);
out.newLine();
}
}
out.close();
}
}
// 播放
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("");
//进行路径的选择判断
String flag=null;
String M[]=new String[5];
int m=0;
String w = "音乐路径.txt";
BufferedReader in=new BufferedReader( new FileReader(w));
String nowid=in.readLine();
while(nowid!=null)
{
M[m]=nowid;
nowid=in.readLine();
m ;
}
in.close();
for(int i=0;i
{
String ww = M[i] ".txt";
BufferedReader nn=new BufferedReader( new FileReader(ww));
String nowd=nn.readLine();
while(nowd!=null)
{
if( nowd.equals(filename) ){
filepath =M[i];
break;
}
else
nowd= nn.readLine();
}
nn.close();
}
File file = new File(filepath filename);
//文件长度
long minute = 0,second = 0;
long total = 0;
try {
AudioFileFormat aff = AudioSystem.getAudioFileFormat(file);
java.util.Map props = aff.properties();
if (props.containsKey("duration"))
total = (long) Math.round((((Long) props.get("duration"))
.longValue())/1000);
//System.out.println("这里显示的是播放的时长\n");
minute=total/60000;
second=total/1000-minute*60;
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
labelfilepath.setText("正在播放:" filename " " "共时长" minute "分 " second "秒");
// 取得文件输入流
audioInputStream = AudioSystem.getAudioInputStream(file);
audioFormat = audioInputStream.getFormat();
// 转换wav文件编码
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();
//playThread.join();
//System.out.printf("\n这里2是%d",judge);
} catch (Exception e) {
//e.printStackTrace();
}
}
public static void main(String args[]) throws IOException {
new SoundPlayerTest();
}
private void clcle(){
if((num 1)
list.select(num 1);
filename = list.getItem(num 1);
hasStop = false;
num=songNum 1;
songNum=num;
System.out.printf("\n这是songnum的显示位置\n%d",songNum);
System.out.printf("\n这是num的显示位置\n%d",num);
play();
}
}
// 播放线程
class PlayThread extends Thread {
private boolean iss;
byte tempBuffer[] = new byte[320];
public void run() {
try {
int cnt;
judge=0;
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;
iss=true;
System.out.println("1" hasStop "\n");
System.out.println("iss" iss "\n");
System.out.println(hasStop);
if(hasStop)
clcle();
}
catch (Exception e) {
e.printStackTrace();
//System.exit(0);
}
//finally{
//if(hasStop)
// clcle();
// }
}
}
}