java 播放mp3文件

java播放mp3格式音频文件

下载第三方jar包,网址:http://www.javazoom.net/javalayer/javalayer.html 

 

 

 

 将jl1.0.0.1.jar拷贝到项目中,并添加到Library 

 

 源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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,代码如下:  

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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();
    }
}

 转载:https://blog.csdn.net/xiaomin1991222/article/details/84904065?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.add_param_isCf&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.add_param_isCf

posted @   海乐学习  阅读(2308)  评论(2编辑  收藏  举报
点击右上角即可分享
微信分享提示