Abilash Ravichandran
Abilash Ravichandran

Reputation: 449

Mp3 player and JMF

I am trying to develop a mp3 player using java.I tried several codes and it ended up in too many errors.So please provide me hints about the code and also help me to configure JMF??

Upvotes: 1

Views: 1791

Answers (1)

pundit
pundit

Reputation: 312

JMF natively does not support mp3 as mp3 is not open source.

If you want to play mp3 file you may do this using jlayer, mp3spi and tritonus libraries.

If you need more informations on these library then let me know.

Please see the below code. With the three libraries added to built path, this code worked for me. Hope this will help you

String mp3File = "path to mp3 file";

public void playMp3(String mp3File ) {
    AudioInputStream din = null;
    AudioInputStream in = null;
    try {
        File file = new File(mp3File);
        in = AudioSystem.getAudioInputStream(file);
        AudioFormat baseFormat = in.getFormat();
        AudioFormat decodedFormat = new AudioFormat(
                AudioFormat.Encoding.PCM_SIGNED,
                baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
                baseFormat.getChannels() * 2, baseFormat.getSampleRate(),
                false);
        din = AudioSystem.getAudioInputStream(decodedFormat, in);
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat);
        line = (SourceDataLine) AudioSystem.getLine(info);

        if (line != null) {
            line.open(decodedFormat);
            byte[] data = new byte[4096];
            // Start
            line.start();

            int nBytesRead;
            while ((nBytesRead = din.read(data, 0, data.length)) != -1) {
                line.write(data, 0, nBytesRead);
                if (flag) {
                    break;
                }
            }
            line.drain();
            line.stop();
            line.close();
            din.close();
        }

    } catch (UnsupportedAudioFileException uafe) {
        JOptionPane.showMessageDialog(null, uafe.getMessage());
        logger.error(uafe);
    } catch (LineUnavailableException lue) {
        JOptionPane.showMessageDialog(null, lue.getMessage());
        logger.error(lue);
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog(null, ioe.getMessage());
        logger.error(ioe);
    } finally {
        if (din != null) {
            try {
                din.close();
            } catch (IOException e) {
            }
        }
        try {
            in.close();
        } catch (IOException ex) {
            logger.error(ex);
        }
    }
 }

Upvotes: 1

Related Questions