首页  >  文章  >  Java  >  如何使用 Java Sound API 和 JMF 播放 MP3 文件?

如何使用 Java Sound API 和 JMF 播放 MP3 文件?

Susan Sarandon
Susan Sarandon原创
2024-10-24 01:50:02556浏览

How to Play MP3 Files Using Java Sound API with JMF?

使用 Java Sound API 播放 MP3

Java Sound API 本身不支持 MP3 文件。要播放 MP3 文件,您可以将基于 JMF 的 mp3plugin.jar 添加到应用程序的运行时类路径。

要播放 MP3 文件,您可以使用以下代码段:

import javax.sound.sampled.*;
import java.io.File;

public class MP3Player {

    public static void main(String[] args) {
        try {
            // Open the MP3 file
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("your_mp3_file.mp3"));

            // Get the audio format
            AudioFormat audioFormat = audioInputStream.getFormat();

            // Create a data line to play the audio
            SourceDataLine dataLine = AudioSystem.getSourceDataLine(audioFormat);
            dataLine.open(audioFormat);

            // Start playing the audio
            dataLine.start();

            // Read the audio data from the file and write it to the data line
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = audioInputStream.read(buffer)) != -1) {
                dataLine.write(buffer, 0, bytesRead);
            }

            // Stop playing the audio
            dataLine.stop();

            // Close the data line and audio input stream
            dataLine.close();
            audioInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

以上是如何使用 Java Sound API 和 JMF 播放 MP3 文件?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn