Java Sound API #2 - MP3 player

The simple audio player at my previous blog plays WAV files, but I want to listen to MP3 files.

% java Player1 BlackDog.mp3
Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
        at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1170)
        at Player1.main(Player1.java:15)
%

JDK implementation does not support MP3 audio format. Fortunately, Sun provides JMF MP3 plugin.

% unzip javamp3-1_0.zip
# cp lib/ext/mp3plugin.jar ${JAVA_HOME}/jre/lib/ext
% java Player1 RockAndRoll.mp3
Exception in thread "main" java.lang.IllegalArgumentException: No line matching interface SourceDataLine supporting format MPEG1L3 44100.0 Hz, unknown bits per sample, stereo, unknown frame size, unknown frame rate,  is supported.
        at javax.sound.sampled.AudioSystem.getLine(AudioSystem.java:459)
        at Player1.main(Player1.java:18)
%

It reads MP3 file, but it has no audio (mixer) line which supports directly MP3 audio format for output. MP3 must be converted to one of the supported audio formats such as PCM. javax.sound.sampled.AudioSystem has getAudioInputStream() method that converts the audio input stream from the original audio format to the specified one.

% cat Player2.java

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.DataLine;
import java.io.File;

public class Player2 {

  private static final int BUFFER_SIZE = 176400; // 44100 x 16 x 2 / 8

  public static void main(String[] args) throws Exception {
    byte[]  buffer = new byte[BUFFER_SIZE];

    AudioInputStream in = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, AudioSystem.getAudioInputStream(new File (args[0])));
    AudioFormat audioFormat = in.getFormat();

    SourceDataLine line = (SourceDataLine) AudioSystem.getLine(new DataLine.Info(SourceDataLine.class, audioFormat));
    line.open(audioFormat);
    line.start();

    while (true) {
      int n = in.read(buffer, 0, buffer.length);
      if (n < 0) {
        break;
      }
      line.write(buffer, 0, n);
    }
    line.drain();
    line.close();
  }
}

% javac Player2
% java Player2 StairwayToHeaven.mp3
%

Now, I can listen to MP3 files with my audio player.

Comments:

Post a Comment:
Comments are closed for this entry.
About

kashmir

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today