>  기사  >  Java  >  JMF와 함께 Java Sound API를 사용하여 MP3 파일을 재생하는 방법은 무엇입니까?

JMF와 함께 Java Sound API를 사용하여 MP3 파일을 재생하는 방법은 무엇입니까?

Susan Sarandon
Susan Sarandon원래의
2024-10-24 01:50:02555검색

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();
        }
    }
}

위 내용은 JMF와 함께 Java Sound API를 사용하여 MP3 파일을 재생하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.