Mp3播放器和JMF

时间:2013-07-02 09:23:19

标签: java swing mp3 javasound

我正在尝试使用java开发一个MP3播放器。我尝试了几个代码并且它出现了太多错误。所以请提供关于代码的提示并帮助我配置JMF ??

1 个答案:

答案 0 :(得分:1)

JMF本身不支持mp3,因为mp3不是开源的。

如果你想播放mp3文件,可以使用jlayer,mp3spi和tritonus库来完成。

如果您需要有关这些库的更多信息,请告知我们。

请参阅以下代码。将三个库添加到构建路径后,此代码对我有用。希望这会对你有所帮助

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);
        }
    }
 }
相关问题