java播放mp3格式音訊檔案
阿新 • • 發佈:2019-01-27
- 下載完成之後解壓提取jl1.0.0.1.jar
- 將jl1.0.0.1.jar拷貝到專案中,並新增到Library
4.原始碼
//Tip: 由於工程名和包名不一樣,最好手打不要盲目複製
package com.lt.music;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.*;
/***
- 音樂播放器類
- @author lt
- time 2016-7-5
*/
public class AudioPlayer{
Player player;
File music;
//構造方法 引數是一個.mp3音訊檔案
public AudioPlayer(File file) {
this.music = file;
}
//播放方法
public void play() throws FileNotFoundException, JavaLayerException {
BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(music));
player = new Player(buffer);
player.play();
}
}
5.如果想把音樂播放作為其他程式的背景音樂,則可以讓其繼承Thread,程式碼如下:
package com.lt.music;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.*;
/***
* 音樂播放器類
* @author lt
* time 2016-7-5
*/
//繼承自執行緒類Thread
public class AudioPlayer extends Thread{
Player player;
File music;
//構造方法
public AudioPlayer(File file) {
this.music = file;
}
//重寫run方法
@Override
public void run() {
super.run();
try {
play();
} catch (FileNotFoundException | JavaLayerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//播放方法
public void play() throws FileNotFoundException, JavaLayerException {
BufferedInputStream buffer =
new BufferedInputStream(new FileInputStream(music));
player = new Player(buffer);
player.play();
}
}