簡體   English   中英

無法播放 Java 中的 .mp3 文件

[英]Having trouble playing .mp3 files in Java

我想做一個簡單的音樂播放器。 所以我從 PC 目錄中過濾了.mp3文件並將它們顯示在JList中。 但是當我 select 來自JList的歌曲時,這首歌沒有播放並顯示這樣的error

java.io.FileNotFoundException: F:\Java in Eclipse\NewMusicPlayer\(song name).mp3 (The system cannot find the file specified)

我的代碼如下

文件過濾代碼:

MP3Player mp3;

private void setMusic() {
    File home = new File("E:\\MUSICS COLLECTION");
    Collection<File> mp3Files = FileUtils.listFiles(home, new String[] { "mp3" }, true);
    @SuppressWarnings("rawtypes")
    DefaultListModel showData = new DefaultListModel();
    for (File file : mp3Files) {
        showData.addElement(file.getName());
        mp3 = new MP3Player(new File(file.getName()));
    }
    musicList.setModel(showData);

}

JList選中項的代碼:

musicList = new JList();
    musicList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent arg0) {
            mp3.play();
        }
    });

更改此行:

mp3 = new MP3Player(new File(file.getName()));

對此:

mp3 = new MP3Player(file);

File#getName返回文件的名稱,而不是絕對路徑。 此外,當您已經擁有file變量時,無需構建新的文件實例。

請記住您的格式。 使用正斜杠保留路徑通常是一種很好的做法。 C:/音樂

為了確保您的路徑不是問題,我會嘗試將一些 mp3 文件加載到某個根目錄或相同的路徑(例如 C:/Music,甚至與源相同的目錄./)。 然后使用上述更改並測試:

    File home = new File("./");
    Collection<File> mp3Files = FileUtils.listFiles(home, new String[] { "mp3" }, true);
    @SuppressWarnings("rawtypes")
    DefaultListModel showData = new DefaultListModel();

    for (File file : mp3Files) {
        showData.addElement(file.getName());
    }
    // the firstFile is just a example. You should store it into an array of Files[]. 
    // or better yet since it's already a Collection use Iterables and get firstElement.
    mp3 = new MP3Player(Iterables.get(mp3Files, 0));
    musicList.setModel(showData);

如果可行,那么您可以嘗試使用不同的路徑。 如果它出錯,那么你就會知道你的路徑搞砸了。

** 修改的。 您的代碼正在播放該 For 循環中的每一首歌曲。 我是即時寫的,但你必須做的是使用你的 mp3Files 集合,並使用 Iterables class 來獲取你想要的任何索引元素。 例如上面寫的抓取 0 索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM