基于Swing的MP3 音乐播放器

/**
 * <br>
 * do what you want to do and never stop it.
 * <br>
 */
package com.luch.music;

import java.awt.BorderLayout;
import java.awt.FileDialog;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
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 java.awt.List;
import java.io.File;

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;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * @author Jack
 * 2012-9-2
 * <br>
 */
public class MusicPlayer extends JFrame {
	
	String filepath;     //播放文件目录
	String filename;//播放文件名称
	AudioInputStream audioInputStream;//文件流 
	AudioFormat audioFormat;//文件格式
	SourceDataLine sourceDataLine;//输出设备
	boolean isStop = true;//控制播放线程
	boolean hasStop = true; //播放线程状态
	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_0));
		menufile.add(menuOpen);
		menufile.addActionListener(new ActionListener() {
			@Override
			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");
		//信息显示
		JPanel panel= new JPanel(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(1);
			}
		});
		setVisible(true);
	}
	/**
	 * open the mp3 file.
	 * @author Jack
	 * @since Sep/3/2012 
	 */
	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);
				}
			}
		}
	}
	
	/**
	 * play the music 
	 * @author Jack
	 * 
	 */
	public void play() {
		try {
			isStop = true;//停止播放线程
			//等待播放线程停止
			System.out.println(" 开始播放:" + filename);
			while(!hasStop) {
				System.out.print(".");
				try {
					Thread.sleep(10);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			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) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}	
	/**
	 * @param args
	 */
	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);
			}
		}
	}
}
如果出现
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file错误
请点击:http://dl.iteye.com/topics/download/234c2199-677b-3c22-92cc-13fddd2bba53链接
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Java Swing 音乐播放器的示例代码: ```java import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javazoom.jlgui.basicplayer.BasicPlayer; import javazoom.jlgui.basicplayer.BasicPlayerException; public class MusicPlayer extends JFrame { private JPanel contentPane; private JLabel lblSongName; private JButton btnPlay; private JButton btnPause; private JButton btnStop; private JFileChooser fileChooser; private BasicPlayer player; private File currentFile; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MusicPlayer frame = new MusicPlayer(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public MusicPlayer() { setTitle("Music Player"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 300, 150); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); lblSongName = new JLabel("No song selected"); lblSongName.setHorizontalAlignment(SwingConstants.CENTER); contentPane.add(lblSongName, BorderLayout.NORTH); JPanel buttonPane = new JPanel(); contentPane.add(buttonPane, BorderLayout.CENTER); btnPlay = new JButton("Play"); btnPlay.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { playSong(); } }); buttonPane.add(btnPlay); btnPause = new JButton("Pause"); btnPause.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pauseSong(); } }); buttonPane.add(btnPause); btnStop = new JButton("Stop"); btnStop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { stopSong(); } }); buttonPane.add(btnStop); fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); player = new BasicPlayer(); } private void playSong() { int result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { currentFile = fileChooser.getSelectedFile(); lblSongName.setText(currentFile.getName()); try { player.open(currentFile); player.play(); } catch (BasicPlayerException e) { e.printStackTrace(); } } } private void pauseSong() { try { player.pause(); } catch (BasicPlayerException e) { e.printStackTrace(); } } private void stopSong() { try { player.stop(); player.close(); lblSongName.setText("No song selected"); } catch (BasicPlayerException e) { e.printStackTrace(); } } } ``` 这个示例使用了 `javax.swing` 和 `javazoom.jlgui.basicplayer` 库。基本的播放器控件是 `JLabel` 和三个 `JButton`,分别用于选择和播放音乐,暂停和继续播放音乐,以及停止播放音乐。播放器使用 `BasicPlayer` 类来实现音乐播放

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值