Home > Net >  Having trouble playing .mp3 files in Java
Having trouble playing .mp3 files in Java

Time:04-27

I want to make a simple music player. So I filtered the .mp3 files from the PC directory and showed them in JList. But when I select the song from JList, the song is not playing and showing error like this

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

My Code is given below

Code of File Filtering :

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

}

Code of JList Selected Item :

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

CodePudding user response:

Change this line:

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

to this:

mp3 = new MP3Player(file);

File#getName returns the name of the file, not the absolute path. Also, there's no need to construct a new file instance when you already have your file variable.

CodePudding user response:

REMEMBER to mind your formatting. It's generally good practice to keep your paths using forward slash. C:/Music

To make sure your path is not the issue I'd try and load some mp3 files into some root directory or the same path (for example C:/Music, or even the same directory as the source ./). Then use the above-mentioned changes and test:

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

If that works then you can try with different paths. If it errors, then you'll know your path is messed up.

** Modified. Your code is playing every single song in that For Loop. I wrote this on the fly, but what you'll have to do is use your mp3Files collection, and use the Iterables class to grab whatever index element you want. For example above written grabs 0 index.

  • Related