JMF音乐播放器

时间:2013-05-17 12:45:01

标签: java file url mp3 jmf

我正在尝试通过JMF库为学校项目创建一个简单的mp3播放器,但我总是有这个错误。该文件的路径是正确的。

java.lang.NullPointerException
        at javax.media.MediaLocator.<init>(MediaLocator.java:37)
        at Mp3Player.run(Mp3Player.java:40)

这是我的代码:

import java.net.URL;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;


public class Mp3Player extends Thread {

   private String filename;
   Player player;

   public Mp3Player(String mp3Filename) {
      this.filename = mp3Filename;
   }

   public void run() {
      try {
         URL url = this.getClass().getClassLoader().getResource(filename);
         MediaLocator locator = new MediaLocator(url);
         player = Manager.createPlayer(locator);
         player.addControllerListener(new ControllerListener() {
            public void controllerUpdate(ControllerEvent event) {
               if (event instanceof EndOfMediaEvent) {
                  player.stop();
                  player.close();
               }
            }
         });
         player.realize();
         player.start();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void main(String[] args) {
      new Mp3Player("C:\\Users\\Aziz\\Music\\music\\a.mp3").start();
   }
}

1 个答案:

答案 0 :(得分:0)

这个字符串URL url = this.getClass().getClassLoader().getResource(filename);似乎很可疑。 尝试使用File中具有方法java.io.*

的课程toURL()
File f = new File ( filename );
MediaLocator locator = new MediaLocator ( f.toURL() );
player = Manager.createPlayer ( locator );