java播放mp3格式音频文件
下载第三方jar包,网址:http://www.javazoom.net/javalayer/javalayer.html
将jl1.0.0.1.jar拷贝到项目中,并添加到Library
源代码
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(); } }
如果想把音乐播放作为其他程序的背景音乐,则可以让其继承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(); } }