JAVA播放MP3的完整代码---简单写个小例子
来源:互联网 发布:freebsd linux 性能 编辑:程序博客网 时间:2024/05/01 03:40
- import javax.media.ControllerEvent;
- import javax.media.ControllerListener;
- import javax.media.NoPlayerException;
- import javax.media.Player;
- import javax.media.Manager;
- import javax.media.MediaLocator;
- import javax.media.EndOfMediaEvent;
- import javax.media.PrefetchCompleteEvent;
- import javax.media.RealizeCompleteEvent;
- import java.io.*;
- import java.util.*;
- public class PlayerMusic implements ControllerListener {
-
- private Player player;
-
- private boolean first,loop;
-
- private String path;
-
- private List<String> mp3List;
-
- private int mp3NO=0;
-
- PlayerMusic(List<String> mp3List)
- {
- this.mp3List=mp3List;
- }
-
-
- public void start()
- {
- try {
- player = Manager.createPlayer(new File(mp3List.get(mp3NO)).toURI().toURL());
- } catch (NoPlayerException e) {
-
- e.printStackTrace();
- System.out.println("不能播放此文件!");
- return;
- } catch (IOException e) {
-
- e.printStackTrace();
- return;
- }
- if(player==null)
- {
- System.out.println("播放文件为空!");
- return;
- }
- player.addControllerListener(this);
-
- player.prefetch();
- }
-
-
-
- public void controllerUpdate(ControllerEvent e) {
-
- if(e instanceof EndOfMediaEvent)
- {
- mp3NO++;
- System.out.println(mp3NO);
- if(mp3NO<mp3List.size())
- {
-
- this.start();
- }
- return;
- }
-
-
- if (e instanceof PrefetchCompleteEvent) {
- System.out.println("内容结束");
- player.start();
- return;
- }
-
-
- if (e instanceof RealizeCompleteEvent) {
- System.out.println("实例化");
-
- return;
- }
-
- }
- public static void main(String[] args)
- {
- List<String> path=new ArrayList<String>();
- path.add("X:\\Song\\只对你有感觉.mp3");
- PlayerMusic play=new PlayerMusic(path);
- play.start();
- }
- }