在好例子网,分享、交流、成长!
您当前所在位置:首页Java 开发实例图形和图像处理 → java 音乐播放器 示例源码(亲测可用)

java 音乐播放器 示例源码(亲测可用)

图形和图像处理

下载此实例
  • 开发语言:Java
  • 实例大小:2.11M
  • 下载次数:63
  • 浏览次数:3668
  • 发布时间:2018-03-17
  • 实例类别:图形和图像处理
  • 发 布 人:qwertyuiop112
  • 文件格式:.zip
  • 所需积分:1

实例介绍

【实例简介】有图形用户界面、能根据本地路径导入本地音乐,项目中含jmf相关 jar包下载

【实例截图】

from clipboard


from clipboard

【核心代码】


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.getItemCount()){
				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<m;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<String, Object> 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.getItemCount()){
					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();
		//   }
			}
		}
	
}


实例下载地址

java 音乐播放器 示例源码(亲测可用)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

第 1 楼 16156464会更好结果 发表于: 2019-05-02 10:25 24
我下载了您的项目,整个项目并未报错,但是无法正常播放音乐,我在您指定的目录下放入了歌曲,打开界面时未显示出歌曲,然后我点击导入歌曲,出现歌曲目录,但是并未播放,我尝试双击歌曲,点击停止歌曲都未能播放出来,请问是什么原因呢?

支持(0) 盖楼(回复)

发表评论

(您的评论需要经过审核才能显示)

查看所有1条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警