首頁 > Java > java教程 > 主體

如何使用 Java Sound API 和 JMF 播放 MP3 檔案?

Susan Sarandon
發布: 2024-10-24 01:50:02
原創
556 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!