1

我正在尝试通过 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();
   }
}
4

1 回答 1

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 );
于 2013-08-04T14:50:09.333 回答