Maison  >  Article  >  Java  >  Comment lire des fichiers MP3 à l'aide de l'API Java Sound avec JMF ?

Comment lire des fichiers MP3 à l'aide de l'API Java Sound avec JMF ?

Susan Sarandon
Susan Sarandonoriginal
2024-10-24 01:50:02555parcourir

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

Lecture de MP3 à l'aide de l'API Java Sound

L'API Java Sound ne prend pas en charge nativement les fichiers MP3. Pour lire des fichiers MP3, vous pouvez ajouter le fichier mp3plugin.jar basé sur JMF au chemin de classe d'exécution de l'application.

Pour lire un fichier MP3, vous pouvez utiliser l'extrait suivant :

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn