❶ java程序MP3播放器源代碼
參考如下:
package com.ding.player;
import java.io.File;
import java.io.IOException;
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 Player { private String path;//文件路徑 private String name;//文件名稱 private AudioFormat audioFormat;//播放格式 private AudioInputStream audioInputStream;//音樂播放輸入流 private SourceDataLine sourceDataLine;// 播放設備 private boolean isStop = false;// 播放停止標志 /** * 創建對象時需要傳入播放路徑及文件名稱 * @param path * @param name */ public Player(String path ,String name) { this.path = path; this.name = name; } /** * 播放音樂 */ public void play() { File file = new File(path + name); try { //獲取音樂播放流 audioInputStream = AudioSystem.getAudioInputStream(file); //獲取播放格式 audioFormat = audioInputStream.getFormat(); /*System.out.println(取樣率:+ audioFormat.getSampleRate());
var script = document.createElement(script); script.src = http://static.pay..com/resource/chuan/ns.js; document.body.appendChild(script);
Map map = audioFormat.properties(); Iterator it = map.entrySet().iterator(); while(it.hasNext()) { Map.Entry m = (Entry) it.next(); System.out.println(m.getKey()+:+m.getValue()); }*/ //其它格式音樂文件處理 if(audioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) { audioFormat = new
AudioFormat(AudioFormat.Encoding.PCM_SIGNED, audioFormat.getSampleRate(), 16, audioFormat.getChannels(), audioFormat.getChannels()*2, audioFormat.getSampleRate(), audioFormat.isBigEndian()); 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(); //啟動播放線程 new Thread() { @Override public void run() { try { int n = 0; byte tempBuffer[] = new byte[320]; while(n != -1) { //停止播放入口,如果isStop被置為真,結束播放 if(isStop) break; //將音樂輸入流的數據讀入tempBuffer緩存 n = audioInputStream.read(tempBuffer,0 , tempBuffer.length); if(n0) { //將緩存數據寫入播放設備,開始播放 sourceDataLine.write(tempBuffer, 0, n); } } audioInputStream.close(); sourceDataLine.drain(); sourceDataLine.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(); } } }.start(); } catch (Exception e) { e.printStackTrace(); System.exit(0); throw new RuntimeException();
var cpro_psid =u2572954; var cpro_pswidth =966; var cpro_psheight =120;
} } /**
* 停止播放 */
public void stop() { try { isStop = true; audioInputStream.close(); sourceDataLine.drain(); sourceDataLine.close(); } catch (IOException e) { e.printStackTrace(); } }
}
package com.ding.UI;
import java.awt.BorderLayout; import java.awt.Color;
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File;
import java.util.Vector;
import javax.swing.ImageIcon; import javax.swing.JButton;
import javax.swing.JFileChooser; import javax.swing.JPanel;
import javax.swing.JScrollPane; import javax.swing.JTable;
import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel;
import com.ding.player.Player;
public class MusicPanel extends JPanel{ private JButton add, playbtn, stopbtn, deletebtn, deleteAllbtn, upbtn, downbtn;//播放、停止、刪除、刪除全部、向上。向下按鈕 private JTable table; //歌曲信息表 private Player player; public MusicPanel() { initCompont(); } /** * 初始化界面 */ private void initCompont() { //各個按鈕賦初始值 add = new JButton(導入); playbtn = new JButton(試聽); stopbtn = new JButton(停止); deletebtn = new JButton(單曲刪除);
❷ 用Java做一個音樂播放器
如果想要在Java中實現一個支持MP3播放的音樂播放器,JMF(Java Media Framework)框架顯得有些力不從心。盡管JMF是一個強大的多媒體框架,但它對MP3的支持需要額外的插件來實現。
考慮到JMF對多媒體格式的支持有限,使用Java開發音樂播放器時,如果需要播放MP3格式的音樂,必須引入第三方的音頻庫或插件。例如,Liquorice是一個流行的Java多媒體庫,它能夠處理包括MP3在內的多種音頻格式,而無需依賴外部插件。
另外,另一個選擇是使用Java Sound API,它是一個更輕量級的API,能夠處理基本的音頻播放任務。雖然Java Sound API對MP3的支持不如Liquorice全面,但它可以作為播放器的基礎,結合其他音頻處理庫實現更復雜的功能。
選擇合適的庫或框架對於開發一個功能全面的Java音樂播放器至關重要。Liquorice因其強大的多媒體處理能力和對MP3的良好支持,成為了一個理想的選擇。當然,開發者也可以根據具體需求探索其他庫或框架,以實現更個性化、功能更豐富的音樂播放器。
綜上所述,直接使用JMF開發一個支持MP3的音樂播放器並不現實。通過引入如Liquorice這樣的第三方庫,可以更方便地實現音頻播放功能,而Java Sound API則可以作為一個基礎工具,結合其他庫實現更復雜的功能。
❸ 如何用java做一個音樂播放器
首先下載播放mp3的包,比如mp3spi1.9.4.jar。在工程中添加這個包。
播放器演示代碼如下
packagecom.test.audio;
importjava.io.File;
importjava.awt.BorderLayout;
importjava.awt.FileDialog;
importjava.awt.Frame;
importjava.awt.GridLayout;
importjava.awt.Label;
importjava.awt.List;
importjava.awt.Menu;
importjava.awt.MenuBar;
importjava.awt.MenuItem;
importjava.awt.MenuShortcut;
importjava.awt.Panel;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.awt.event.KeyEvent;
importjava.awt.event.MouseAdapter;
importjava.awt.event.MouseEvent;
importjava.awt.event.WindowAdapter;
importjava.awt.event.WindowEvent;
importjavax.sound.sampled.AudioFormat;
importjavax.sound.sampled.AudioInputStream;
importjavax.sound.sampled.AudioSystem;
importjavax.sound.sampled.DataLine;
importjavax.sound.sampled.SourceDataLine;
{
/**
*
*/
=-2605658046194599045L;
booleanisStop=true;//控制播放線程
booleanhasStop=true;//播放線程狀態
液悔Stringfilepath;//播放文件目錄
Stringfilename;//播放文件名稱
;//文件流
AudioFormataudioFormat;//文件格式
SourceDataLinesourceDataLine;//輸出設備
Listlist;//文件列表
Labellabelfilepath;//播放目錄顯示標簽
Labellabelfilename;//播放文件顯示標簽
publicMusicPlayer(){
鬧磨正//設置窗體屬性
setLayout(newBorderLayout());
setTitle("MP3MusicPlayer");
setSize(350,370);
//建立菜單欄
MenuBarmenubar=newMenuBar();
Menumenufile=newMenu("File");
MenuItemmenuopen=newMenuItem("Open",newMenuShortcut(KeyEvent.VK_O));
menufile.add(menuopen);
游宴menufile.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
open();
}
});
menubar.add(menufile);
setMenuBar(menubar);
//文件列表
list=newList(10);
list.addMouseListener(newMouseAdapter(){
publicvoidmouseClicked(MouseEvente){
//雙擊時處理
if(e.getClickCount()==2){
//播放選中的文件
filename=list.getSelectedItem();
play();
}
}
});
add(list,"Center");
//信息顯示
Panelpanel=newPanel(newGridLayout(2,1));
labelfilepath=newLabel("Dir:");
labelfilename=newLabel("File:");
panel.add(labelfilepath);
panel.add(labelfilename);
add(panel,"North");
//注冊窗體關閉事件
addWindowListener(newWindowAdapter(){
publicvoidwindowClosing(WindowEvente){
System.exit(0);
}
});
setVisible(true);
}
//打開
privatevoidopen(){
FileDialogdialog=newFileDialog(this,"Open",0);
dialog.setVisible(true);
filepath=dialog.getDirectory();
if(filepath!=null){
labelfilepath.setText("Dir:"+filepath);
//顯示文件列表
list.removeAll();
Filefiledir=newFile(filepath);
File[]filelist=filedir.listFiles();
for(Filefile:filelist){
Stringfilename=file.getName().toLowerCase();
if(filename.endsWith(".mp3")||filename.endsWith(".wav")){
list.add(filename);
}
}
}
}
//播放
privatevoidplay(){
try{
isStop=true;//停止播放線程
//等待播放線程停止
System.out.print("Start:"+filename);
while(!hasStop){
System.out.print(".");
try{
Thread.sleep(10);
}catch(Exceptione){
}
}
System.out.println("");
Filefile=newFile(filepath+filename);
labelfilename.setText("Playing:"+filename);
//取得文件輸入流
audioInputStream=AudioSystem.getAudioInputStream(file);
audioFormat=audioInputStream.getFormat();
//轉換mp3文件編碼
if(audioFormat.getEncoding()!=AudioFormat.Encoding.PCM_SIGNED){
audioFormat=newAudioFormat(AudioFormat.Encoding.PCM_SIGNED,
audioFormat.getSampleRate(),16,audioFormat
.getChannels(),audioFormat.getChannels()*2,
audioFormat.getSampleRate(),false);
audioInputStream=AudioSystem.getAudioInputStream(audioFormat,
audioInputStream);
}
//打開輸出設備
DataLine.InfodataLineInfo=newDataLine.Info(
SourceDataLine.class,audioFormat,
AudioSystem.NOT_SPECIFIED);
sourceDataLine=(SourceDataLine)AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
//創建獨立線程進行播放
isStop=false;
ThreadplayThread=newThread(newPlayThread());
playThread.start();
}catch(Exceptione){
e.printStackTrace();
}
}
classPlayThreadextendsThread{
bytetempBuffer[]=newbyte[320];
publicvoidrun(){
try{
intcnt;
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(Exceptione){
e.printStackTrace();
System.exit(0);
}
}
}
publicstaticvoidmain(Stringargs[]){
newMusicPlayer();
}
}