2013-05-17 198 views
1

我試圖通過JMF庫爲一個學校項目創建一個簡單的MP3播放器,但我總是有這個錯誤。該文件的路徑是正確的。JMF音樂播放器

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(); 
    } 
} 

回答

0

此字符串URL url = this.getClass().getClassLoader().getResource(filename);似乎可疑。 嘗試在java.io.*使用File類,有方法toURL()

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