Java Sound API does not natively support MP3 files. To play MP3 files, you can add the JMF based mp3plugin.jar to the application's run-time classpath.
To play an MP3 file, you can use the following snippet:
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(); } } }
The above is the detailed content of How to Play MP3 Files Using Java Sound API with JMF?. For more information, please follow other related articles on the PHP Chinese website!