導航:首頁 > 編程語言 > java音樂切換代碼

java音樂切換代碼

發布時間:2023-01-29 20:44:35

A. 跪求java 音樂播放的代碼啊,完美運行的就行

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.AWTException;
import java.awt.Frame;
import java.awt.SystemTray;
import java.awt.TrayIcon;
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 java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.*;
public class bofan_2 extends JFrame implements ActionListener
{
boolean looping=false;
File file1=null;
AudioClip sound1;
AudioClip chosenClip;
private JComboBox box1=null; //歌曲列表
private JButton butbofan=null; //播放
private JButton butboxhuan=null; //循環播放
private JButton buttinzi=null; //停止
private JButton butshan=null; //上一首
private JButton butzhantin=null; //暫停
private JButton butxia=null; //下一首
private TrayIcon trayIcon;//托盤圖標
private SystemTray systemTray;//系統托盤
public bofan_2()
{
this.setSize(420,400);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setLayout(null);
box1=new JComboBox();
box1.addItem("傷心太平洋");
box1.addItem("勁爆的士高");
box1.addItem("老夫少妻");
box1.addItem("愛不再來");
box1.addItem("抽身");
box1.addItem("傷心城市");
box1.addItem("二零一二");
box1.addItem("精忠報國");
box1.addItem("秋沙");
box1.addItem("吻別");
box1.addItem("音樂瘋起來");
box1.setBounds(10,20,150,20);

butbofan=new JButton("播放");
butbofan.addActionListener(this);
butbofan.setBounds(165,50,60,20);

butboxhuan=new JButton("循環播放");
butboxhuan.addActionListener(this);
butboxhuan.setBounds(230,50,90,20);

buttinzi=new JButton("停止");
buttinzi.setEnabled(false);
buttinzi.addActionListener(this);
buttinzi.setBounds(335,50,60,20);

butshan=new JButton("上一首");
butshan.addActionListener(this);
butshan.setBounds(165,90,80,20);

butzhantin=new JButton("暫停");
butzhantin.setEnabled(false);
butzhantin.addActionListener(this);
butzhantin.setBounds(250,90,60,20);

butxia=new JButton("下一首");
butxia.addActionListener(this);
butxia.setBounds(320,90,80,20);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(box1);
this.getContentPane().add(butbofan);
this.getContentPane().add(butboxhuan);
this.getContentPane().add(buttinzi);
this.getContentPane().add(butshan);
this.getContentPane().add(butzhantin);
this.getContentPane().add(butxia);
try {
UIManager.setLookAndFeel("org.jvnet.substance.skin.");
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} catch (InstantiationException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
} catch ( e)
{
e.printStackTrace();
}

setSize(450,450);

systemTray = SystemTray.getSystemTray();//獲得系統托盤的實例
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
trayIcon = new TrayIcon(ImageIO.read(new File("004.jpg")));
systemTray.add(trayIcon);//設置托盤的圖標,0.gif與該類文件同一目錄
}
catch (IOException e1)
{
e1.printStackTrace();
}
catch (AWTException e2)
{
e2.printStackTrace();
}

this.addWindowListener(
new WindowAdapter(){
public void windowIconified(WindowEvent e)
{
dispose();//窗口最小化時dispose該窗口
}
});

trayIcon.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e){
if(e.getClickCount() == 2)//雙擊托盤窗口再現
setExtendedState(Frame.NORMAL);
setVisible(true);
}
});

this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source== butbofan)
{
System.out.println((String) box1.getSelectedItem());
file1=new File((String) box1.getSelectedItem()+".wav");
butboxhuan.setEnabled(true);
buttinzi.setEnabled(true);
butzhantin.setEnabled(true);
butzhantin.setText("暫停");
try {
sound1 = Applet.newAudioClip(file1.toURL());
chosenClip = sound1;
} catch(OutOfMemoryError er){
System.out.println("內存溢出");
er.printStackTrace();
} catch(Exception ex){
ex.printStackTrace();
}
chosenClip.play();
this.setTitle("正在播放"+(String) box1.getSelectedItem());
}
if (source== butboxhuan)
{
file1=new File((String) box1.getSelectedItem()+".wav");
try {
sound1 = Applet.newAudioClip(file1.toURL());
chosenClip = sound1;
} catch(OutOfMemoryError er){
System.out.println("內存溢出");
er.printStackTrace();
} catch(Exception ex){
ex.printStackTrace();
}
looping = true;
chosenClip.loop();
butboxhuan.setEnabled(false);
buttinzi.setEnabled(true);
butzhantin.setText("暫停");
this.setTitle("正在循環播放"+(String) box1.getSelectedItem());
}
if (source== buttinzi)
{
if (looping)
{
looping = false;
chosenClip.stop();
butboxhuan.setEnabled(true);
butzhantin.setText("暫停");
} else {
chosenClip.stop();
}
buttinzi.setEnabled(false);
this.setTitle("停止播放");
}
if(source==butshan)
{
butzhantin.setText("暫停");
}
if(source==butzhantin)
{
buttinzi.setEnabled(false);
butzhantin.setText("繼續");
if(source==butzhantin)
{
butzhantin.setText("暫停");
}
}
if(source==butxia)
{
butzhantin.setText("暫停");
}
}
public static void main(String[] args)
{
bofan_2 xx=new bofan_2();
}
}
/*
可以用載入聲音文件的方法:
第一幀:mysound= new Sound();
mysound.attachSound(聲音id名字);
ptime = 0;
播放按鈕as:
on(release){
mysound.start(ptime);
}
暫停按鈕as:
on(release){
ptime = mysound.position/1000;
mysound.stop();
}
*/

B. 如何用JAVA代碼完成AMR格式到MP3格式的轉換

真正的萬能視頻轉換工具,扔掉那些所謂的什麼白金大師吧!!!
綠色(安裝到其他機器,拷過來也可以使用)!無插件!同濟學子開發的免費軟體,更新快!
MediaCoder是一個免費的通用音頻/視頻批量轉碼工具,它將眾多來自開源社區的優秀音頻視頻編解碼器和工具整合為一個通用的解決方案,它可以將音頻、視頻文件在各種格式之間進行轉換。
特點聚焦:
直接、批量地在眾多音頻視頻壓縮格式和容器格式之間進行轉換
無需安裝任何媒體播放器或編碼器
純綠色軟體,不在系統中注冊任何組件
完全使用Win32
SDK開發,高效、緊湊,不依賴於任何中間層(如.NET,
JAVA等)
典型應用:
提高壓縮率/減小文件尺寸
將無損音頻或者高碼率的有損音頻轉換轉換為較低碼率的有損音頻,以便用攜帶型數字音樂播放設備欣賞
轉換至可在各種設備(如手機、PDA、MP4播放器、VCD/DVD播放機)上播放的格式
提取視頻文件中的音軌
保存CD/VCD/DVD
支持的輸入格式:
MP3,
Ogg
Vorbis,
AAC,
AAC+/Parametric
Stereo,
AMR
NB/WB,
MusePack,
WMA,
RealAudio
FLAC,
WavPack,
Monkey's
Audio
(APE,
APL),
OptimFrog,
AAC
Lossless,
WMA
Lossless,
WAV
H.264,
Xvid,
DivX
4/5,
MPEG
1/2/4,
H.263,
3ivx,
RealVideo,
Windows
Media
Video
7/8/9,
DV
AVI,
MPEG/VOB,
Matroska,
MP4,
RealMedia,
ASF/WMV,
Quicktime
MOV,
OGM
CD,
VCD,
DVD,
CUE
Sheets
支持的輸出格式:
MP3,
Ogg
Vorbis,
AAC,
AAC+/Parametric
Stereo,
AMR
NB/WB,
MusePack,
WMA
FLAC,
WavPack,
Monkey's
Audio
(APE,
APL),
OptimFrog,
WMA
Lossless,
WAV
H.264,
Xvid,
DivX
4/5,
MPEG
1/2/4,
H.263,
Flash
Video,
etc.
AVI,
MPEG/VOB,
Matroska,
MP4,
PMP
(PSP媒體播放器格式)
另外,虛機團上產品團購,超級便宜

C. java音樂播放

Applet我沒有學過-------現在都用Swing了,AWT都很少用的。
我跑了下你的程序,你的錯誤在這:
sound=getAudioClip(getDocumentBase(),"test.mp3");
也就是AudioClip 對象沒有創建成功!

在監聽器中觸發事件的時候,你首先要判斷AudioClip 不為空,然後才能進行播放!

if (obj == plays) {
if (sound != null) {
sound.play();
} else {
sound = getAudioClip(getDocumentBase(), "D:\\lalala.wma");
sound.play();
}

} else if (obj == stops) {
。。。。。
這樣寫是對的寫法
但是sound = getAudioClip(getDocumentBase(), "D:\\lalala.wma");
還是沒有構建成功。所以,你構建AudioClip估計是錯誤的寫法。

Appletde API太老了,我沒有看,所以給你個Swing寫的代碼,你跑下看看,編譯通過的。建議你不要用Applet了!
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.swing.*;

public class MusicDemo extends JFrame implements ActionListener {
Player player = null;
String tilte = "音樂播放器";

public MusicDemo(String title) {
super(title); // 設置顯示標題(必須)
setResizable(false);// 設置是否可以拖放窗口大小
File mufile = new File("D:\\Lovinyou.mp3");
try {
if (player == null) {
if (mufile.exists()) {
MediaLocator locator = new MediaLocator("file:"
+ mufile.getAbsolutePath());
player = Manager.createRealizedPlayer(locator);
player.prefetch();
}
}
// player.addControllerListener(this);
player.start();// 開始播放

add(player.getControlPanelComponent(), "South");
double lx = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
double ly = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
setLocation((int) lx / 2 - 200, (int) ly / 2 - 150);// 設置顯示位置(必須)
// 設置frame的大小(必須)
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 關閉按鈕退出程序(必須)
setVisible(true);// (必須)
} catch (Exception e) {
e.getStackTrace();
}
}

public String getTilte() {
return tilte;
}

public void setTilte(String tilte) {
this.tilte = tilte;
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub

}
public static void main(String[] args) {
MusicDemo d = new MusicDemo("播放音樂");
}
}

記得在File mufile = new File("D:\\Lovinyou.mp3"); 這地方換為你音樂的路徑

D. java中我想實現用按鈕來控制音樂播放與停止 下面是我的代碼 但實現不了播放和停止 誰能幫我解決一下嗎

我幫你把程序改完了,可以實現用按鈕來控制音樂播放與停止了,你看看吧。
import java.applet.Applet;

import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URI;
import java.net.URL;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class f extends JFrame implements ActionListener {
private static final String AudioClip = null;
private JButton Oj;
private JButton Oj1;
AudioClip clip =null;
File musicFile;
URI uri;
URL url;
private void f() throws InterruptedException{
musicFile = new File("E:\\JAVA\\new1\\celine dion - falling into you.wav");
uri = musicFile.toURI();
try {
url = uri.toURL();
} catch (Exception e) {
}
clip=Applet.newAudioClip(url);
//clip.play();
}
f() {
this.setSize(800, 600);
this.setResizable(false);
JPanel p = new JPanel();
this.setContentPane(p);
this.setVisible(true);
Oj = new JButton("開始");
Oj1 = new JButton("結束");

this.setVisible(true);
Oj.addActionListener(this);
Oj1.addActionListener(this);
this.add(Oj);
this.add(Oj1);
}
public static void main(String[] args) throws InterruptedException {
f ff=new f();
ff.f();
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == Oj) {
System.out.println("進入游戲界面");

play();
} else if (e.getSource() == Oj1) {
System.out.println("退出遊戲");
stop();
//System.exit(0);
}
}
public void play() {
if (clip != null)
( (java.applet.AudioClip) clip).play();
}
public void stop() {
if (clip != null)
( (java.applet.AudioClip) clip).stop();
}
}

E. 求一個JAVA音樂播放器的源代碼

import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.PrefetchCompleteEvent;
import javax.media.RealizeCompleteEvent;
import javax.media.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MediaPlayer extends JFrame implements ActionListener,
ItemListener, ControllerListener {
String title;

Player player;
boolean first = true, loop = false;
Component vc, cc;
String currentDirectory=null;
// 構造函數,其中包括了設置響應窗口事件的監聽器。
MediaPlayer(String title) {
super(title);
/* 關閉按鈕的實現。。 */
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}

public void windowClosed(WindowEvent e) {
if (player != null)
player.close();
System.exit(0);
}

});
// 調用程序菜單欄的方法成員完成菜單的布置
setupMenu();
setSize(400, 400);
setVisible(true);
}

// 本方法用以設置程序菜單欄
public void setupMenu() {
// 設置一個菜單
Menu f = new Menu("文件");
// 往設置的菜單添加菜單項
MenuItem mi = new MenuItem("打開");
f.add(mi);
mi.addActionListener(this);
f.addSeparator();
CheckboxMenuItem cbmi = new CheckboxMenuItem("循環", false);
cbmi.addActionListener(this);
f.add(cbmi);
f.addSeparator();
MenuItem ee = new MenuItem("退出");
ee.addActionListener(this);
f.add(ee);
f.addSeparator();

Menu l = new Menu("播放列表");
Menu c = new Menu("播放控制");
MenuItem move = new MenuItem("播放");
move.addActionListener(this);
c.add(move);
c.addSeparator();
MenuItem pause = new MenuItem("暫停");
pause.addActionListener(this);
c.add(pause);
c.addSeparator();
MenuItem stop = new MenuItem("停止");
stop.addActionListener(this);
c.add(stop);
c.addSeparator();
// 設置一個菜單欄
MenuBar mb = new MenuBar();
mb.add(f);
mb.add?;
mb.add(l);
// 將構造完成的菜單欄交給當前程序的窗口;
setMenuBar(mb);
}

// 動作時間響應成員;捕捉發送到本對象的各種事件;
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String cufile, selectfile, currentDirectory;
if (e.getActionCommand().equals("退出")) {
// 調用dispose以便執行windowClosed
dispose();
return;
}
// 此事表明擁護選擇了「播放」命令;
// 如果當前有一個文件可以播放則執行播放命令;
if (e.getActionCommand().equals("播放")) {
if (player != null) {
player.start();
}
return;
}
// 如果當前正在播放某一文件,則執行暫停;
if (e.getActionCommand().equals("暫停")) {
if (player != null) {
player.stop();
}
return;
}
// 停止命令的響應;
if (e.getActionCommand().equals("停止")) {
if (player != null) {
player.stop();
player.setMediaTime(new Time(0));
}
return;
}
// 用戶選擇要播放的媒體文件
if (e.getActionCommand().equals("打開")) {
FileDialog fd = new FileDialog(this, "打開媒體文件", FileDialog.LOAD);
// fd.setDirectory(currentDirectory);

2008-2-6 02:46 回復

肆方茉莉
62位粉絲
6樓

fd.setVisible(true);
// 如果用戶放棄選擇文件,則返回
if (fd.getFile() == null) {
return;
}
// 保存了所選文件的名稱及其路徑名稱已被稍後使用
// 同時設置當前文件夾路徑
selectfile = fd.getFile();
currentDirectory = fd.getDirectory();
cufile = currentDirectory + selectfile;
// 將用戶選擇的文件作為一個菜單項加入播放列表,該菜單項名為該文件名;
// 被點擊後給出的命令串是該文件的全路徑名
MenuItem mi = new MenuItem(selectfile);
mi.setActionCommand(cufile);
MenuBar mb = getMenuBar();
Menu m = mb.getMenu(2);
mi.addActionListener(this);
m.add(mi);
} else {
// 程序邏輯運行到次表示用戶選擇了一個「播放列表」中的媒體文件
// 此時可以通過如下動作獲得該文件的全路徑名
cufile = e.getActionCommand();
selectfile = cufile;
}
// 如果存在一個播放器,則先將其關閉,稍後再重新創建
// 創建播放器時需要捕捉一些異常
if (player != null) {
player.close();
}
try {
player = Manager.createPlayer(new MediaLocator("file:" + cufile));
} catch (Exception e2) {
System.out.println(e2);
return;
}/*
* catch(NoPlayerException e2){ System.out.println("不能找到播放器");
* return ; }
*/
if (player == null) {
System.out.println("無法創建播放器");
return;
}
first = false;
setTitle(selectfile);
// 設置處理播放控制器實際的對象;
/**/
player.addControllerListener(this);
player.prefetch();
}

// 菜單狀態改變事件的響應函數;
public void itemStateChanged(ItemEvent arg0) {
// TODO Auto-generated method stub

}
public static void main(String[] args) {
// TODO Auto-generated method stub
new MediaPlayer("播放器");
}

// 調用繪圖函數進行界面的繪制 // public void update() {
// }
// 繪圖函數成員 //public void paint(Graphics g) {
// }
public void controllerUpdate(ControllerEvent e) {
// TODO Auto-generated method stub
Container tainer = getContentPane();
// 調用player.close()時ControllerClosedEvent事件出現
// 如果存在視覺部件,則該部件應該拆除(為了一致起見,我們對控制面版部件也執行同樣的操作,下一次需要時再構造)
if (e instanceof ControllerClosedEvent) {
if (vc != null) {
remove(vc);
vc = null;
}
if (cc != null) {
remove(cc);
cc = null;
}
}

// 播放結束時,將播放指針置於文件之首,如果設定了循環播放,則再次啟動播放器;
if (e instanceof EndOfMediaEvent) {
player.setMediaTime(new Time(0));
if (loop) {
player.start();
}
return;
}

// PrefetchCompletEvent事件發生後調用start,正式啟動播放
if (e instanceof PrefetchCompleteEvent) {
player.start();
return;
}

// 本事件表示由於播放的資源已經確定;此時要將媒體的圖形conmopnent
// 如果有顯示出來,同時將播放器player的控制顯示到窗口裡;
if (e instanceof RealizeCompleteEvent) {
// 如果媒體中有圖像,將對應圖像component載入窗體;
vc = player.getVisualComponent();
if (vc != null)
tainer.add(vc, BorderLayout.CENTER);
// 將對應控制器component載入窗體;
cc = player.getControlPanelComponent();
cc.setBackground(Color.blue);
if (cc != null)
tainer.add(cc, BorderLayout.SOUTH);
// 有一些特殊媒體在播放時提供另外的控制手段,將控制器一並加入窗口;
/*
* gc=player.getGainControl(); gcc=gc.getControlComponent();
* if(gcc!=null) tainer.add(gcc,BorderLayout.NORTH);
*/
// 根據媒體文件中是否有圖像,設定相應的窗口大小
if (vc != null) {
pack();
return;
} else {
setSize(300, 75);
setVisible(true);
return;
}
}

} }

F. Java怎麼實現音樂播放

java swt實現播放音樂代碼如下:

public void play(String Filename)
{
try{
// 用輸入流打開一音頻文件
InputStream in = new FileInputStream(Filename);//FIlename 是你載入的聲音文件如(「game.wav」)
// 從輸入流中創建一個AudioStream對象
AudioStream as = new AudioStream(in);
AudioPlayer.player.start(as);//用靜態成員player.start播放音樂
//AudioPlayer.player.stop(as);//關閉音樂播放
//如果要實現循環播放,則用下面的三句取代上面的「AudioPlayer.player.start(as);」這句
/*AudioData data = as.getData();
ContinuousAudioDataStream gg= new ContinuousAudioDataStream (data);
AudioPlayer.player.start(gg);// Play audio.
*/
//如果要用一個 URL 做為聲音流的源(source),則用下面的代碼所示替換輸入流來創建聲音流:
/*AudioStream as = new AudioStream (url.openStream());
*/
} catch(FileNotFoundException e){
System.out.print("FileNotFoundException ");
} catch(IOException e){
System.out.print("有錯誤!");
}
}

G. 給java程序加背景音樂的代碼~

一樓的回答說對了一部分,主要還是多線程的問題.
我的畢業設計也是做的一個小游戲程序--坦克大戰,當初游戲邏輯界面都完成了想加入音頻的時候也遇到了困難,最開始想到了多線程處理,也就是自身游戲的繪圖線程佔用著主線程,如果此時再在同一線程播放音頻的話肯定會造成音頻流或者繪圖類paint阻塞,所以這時要為音頻加入一個單獨額外的線程,已達到避免線程阻塞的作用.
但是此時還是會出現音頻不流暢的情況(當然,大多情況是出現短暫音效後便消失),主要問題在於Java在利用線程讀取音頻的時候,是通過流的方式讀取的,此時可以考慮在程序載入之前先「預載」一次音頻,當需要的時候再調用它的播放線程,利用流處理.這么做的好處是將音頻存放在內存中,當需要的時候能正常的出現.當然,後面這段情況是在你運用到了多線程的時候才會出現的。
找了下畢設時的代碼,如下:
/**
*該方法為音頻流緩沖方法,在調用音頻播放線程時調用
*/
public BufferedInputStream loadBomb(){
BufferedInputStream bufbomb = null;
try{
File dir = new File("D:/java/TankWar2.6/"); //所要播放文件的路徑
File fObject = new File(dir,"bomb.wav"); //音頻名
FileInputStream file = new FileInputStream(fObject);
bufbomb = new BufferedInputStream(file);
}catch(IOException e) {
System.out.println(e.getMessage());
}
return bufbomb;
}

/**
* 緩沖完畢的核爆音頻播放線程
*/
private class BombMusic implements Runnable{ //通過流讀取聲音文件
BufferedInputStream buf;
public void run(){
buf = loadBomb();
try{
AudioStream audio = new AudioStream(buf);
AudioPlayer.player.start(audio);
}catch(IOException e){
e.printStackTrace();
}
}
}

H. 求在java中添加背景音樂的代碼

不知道你是在java里哪添加?Swing界面中嗎?
下面這個是我之前做Swing界面程序時添加音樂的代碼,專希望對你有幫助屬
AudioClip[] musics;//定義音樂集合
musics = new AudioClip[2];//初始化
URL url1 = this.getClass().getResource("/ReadyGo.WAV"); //定義音樂文件地址
URL url2 = this.getClass().getResource("/back1.mid"); //定義音樂文件地址
musics[0] = JApplet.newAudioClip(url1);
musics[1] = JApplet.newAudioClip(url2);
musics[0].play();//音樂開始執行
musics[1].stop();//停止播放

I. java大神求解啊,如何用java編寫一個音樂播放器,然後播放器裡面的歌可以順序播放的。

參考代碼如下
首先下載播放mp3的包,比如mp3spi1.9.4.jar。在工程中添加這個包。
播放器演示代碼如下
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 {
/**
*
*/
private static final long serialVersionUID = -2605658046194599045L;
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 Music Player");
setSize(350, 370);

// 建立菜單欄
MenuBar menubar = new MenuBar();
Menu menufile = new Menu("File");
MenuItem menuopen = new MenuItem("Open", 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("Dir:");
labelfilename = new Label("File:");
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("Dir:" + 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("Start:" + filename);
while (!hasStop) {
System.out.print(".");
try {
Thread.sleep(10);
} catch (Exception e) {
}
}
System.out.println("");
File file = new File(filepath + filename);
labelfilename.setText("Playing:" + 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();
}
}

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);
}
}
}

public static void main(String args[]) {
new MusicPlayer();
}
}

J. java安卓開發中raw內音樂播放上一首下一首怎麼實現

先做一個播放列表,,,,,,在播放完的事件中,播放下一首
~
~
~
~

閱讀全文

與java音樂切換代碼相關的資料

熱點內容
win10系統怎麼製作鏡像文件 瀏覽:251
二戰德國軍官與穿越女主 瀏覽:993
釘釘手機端使用教程 瀏覽:396
如何把1列數據非零挑選出來 瀏覽:426
cnc編程中分號怎麼錄入 瀏覽:640
ppt中嵌入pdf文件夾 瀏覽:537
excel如何提取圖片里的數據 瀏覽:439
手機版工資表格是什麼app 瀏覽:703
以下文件格式中是動畫格式的是 瀏覽:40
火車頭採集js 瀏覽:599
求個免費網站在線觀看 瀏覽:98
韓國激情電影百合電影 瀏覽:113
熙和宇還演過什麼電影 瀏覽:716
pr在哪裡設置代理文件路徑 瀏覽:663
插入桌面文件找不到 瀏覽:704
和電商有關電影 瀏覽:879
化理片電影 瀏覽:367
電腦顯示mrt找不到文件 瀏覽:291
看電影的布叫什麼 瀏覽:513
泰國洗澡露天電影 瀏覽:821

友情鏈接