java播放mp3格式音频文件

时间:2022-06-17 15:12:22
  1. 下载第三方jar包,网址:http://www.javazoom.net/javalayer/javalayer.html
    java播放mp3格式音频文件
  2. 下载完成之后解压提取jl1.0.0.1.jar
    java播放mp3格式音频文件
  3. 将jl1.0.0.1.jar拷贝到项目中,并添加到Library
    java播放mp3格式音频文件
    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();
}
}