javamp3jlayer

Why is this program not playing my music files?


I was trying to create a basic music player in Java using JLayer library, but it doesn't seem to work. Nothing is played when I open a file (.mp3) through JFileChooser. Below is the code for my application. Please tell me what's wrong in it.

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.swing.JFileChooser;
import javazoom.jl.player.Player;
import javazoom.jl.decoder.JavaLayerException;

class MusicPlayer
{
public void Player()
{
    JFileChooser chooser = new JFileChooser();

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        try
        {
            File track = chooser.getSelectedFile();
            FileInputStream trackstream = new FileInputStream(track);
            BufferedInputStream bufferedtrack = new BufferedInputStream(trackstream);

            try
            {
                Player player = new Player(bufferedtrack);
            }
            catch(JavaLayerException e)
            {
                System.out.println("Can't open file!");
            }

        }

        catch(FileNotFoundException e)
        {
        }
    } 
    else {

    }
 }
}

public class PlayerApp {



public static void main(String[] args) {

    new MusicPlayer().Player();

}

}

Solution

  • You did miss out player.play() of the Player to start playing the requested file.

    try 
    {
        Player player = new Player(bufferedtrack);
        player.play(); // add this line
    }
    catch(JavaLayerException e)
    {
        System.out.println("Can't open file!");
    }
    

    Also, method names are commonly written in camel-case (first letter lowercase). I recommend to rename your method void Player() to something like void loadDialogAndPlayFile().