8

My code to convert mp3 to wav is:

package audio1;

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

public class NewClass {
    public static void main(String [] args){
        try{
            AudioFileFormat inputFileFormat = AudioSystem.getAudioFileFormat(new File("c:\\1.mp3"));
            AudioInputStream ais = AudioSystem.getAudioInputStream(new File("c:\\1.mp3"));

            AudioFormat audioFormat = ais.getFormat();

            System.out.println("File Format Type: "+inputFileFormat.getType());
            System.out.println("File Format String: "+inputFileFormat.toString());
            System.out.println("File lenght: "+inputFileFormat.getByteLength());
            System.out.println("Frame length: "+inputFileFormat.getFrameLength());
            System.out.println("Channels: "+audioFormat.getChannels());
            System.out.println("Encoding: "+audioFormat.getEncoding());
            System.out.println("Frame Rate: "+audioFormat.getFrameRate());
            System.out.println("Frame Size: "+audioFormat.getFrameSize());
            System.out.println("Sample Rate: "+audioFormat.getSampleRate());
            System.out.println("Sample size (bits): "+audioFormat.getSampleSizeInBits());
            System.out.println("Big endian: "+audioFormat.isBigEndian());
            System.out.println("Audio Format String: "+audioFormat.toString());

            AudioInputStream encodedASI = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, ais);

            try{
                int i = AudioSystem.write(encodedASI, AudioFileFormat.Type.WAVE, new File("c:\\converted.wav"));
                System.out.println("Bytes Written: "+i);
            }catch(Exception e){
                e.printStackTrace();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

But I am getting following output:

File Format Type: MP3
File Format String: MP3 (.mp3) file, byte length: 9631340, data format: MPEG1L3 48000.0 Hz, unknown bits per sample, stereo, unknown frame size, 41.666668 frames/second, , frame length: 10030
File lenght: 9631340
Frame length: 10030
Channels: 2
Encoding: MPEG1L3
Frame Rate: 41.666668
Frame Size: -1
Sample Rate: 48000.0
Sample size (bits): -1
Big endian: true
Audio Format String: MPEG1L3 48000.0 Hz, unknown bits per sample, stereo, unknown frame size, 41.666668 frames/second, 
java.lang.ArrayIndexOutOfBoundsException: 1
        at org.tritonus.sampled.convert.javalayer.MpegFormatConversionProvider$DecodedMpegAudioInputStream$DMAISObuffer.append(MpegFormatConversionProvider.java:386)
        at javazoom.jl.decoder.Obuffer.appendSamples(Unknown Source)
        at javazoom.jl.decoder.SynthesisFilter.compute_pcm_samples(Unknown Source)
        at javazoom.jl.decoder.SynthesisFilter.calculate_pcm_samples(Unknown Source)
        at javazoom.jl.decoder.LayerIIIDecoder.decode(Unknown Source)
        at javazoom.jl.decoder.LayerIIIDecoder.decodeFrame(Unknown Source)
        at javazoom.jl.decoder.Decoder.decodeFrame(Unknown Source)
        at org.tritonus.sampled.convert.javalayer.MpegFormatConversionProvider$DecodedMpegAudioInputStream.execute(MpegFormatConversionProvider.java:307)
        at org.tritonus.share.TCircularBuffer.read(TCircularBuffer.java:138)
        at org.tritonus.share.sampled.convert.TAsynchronousFilteredAudioInputStream.read(TAsynchronousFilteredAudioInputStream.java:194)
        at javax.sound.sampled.AudioInputStream.read(AudioInputStream.java:292)
        at com.sun.media.sound.PCMtoPCMCodec$PCMtoPCMCodecStream.read(PCMtoPCMCodec.java:506)
        at com.sun.media.sound.SunFileWriter$NoCloseInputStream.read(SunFileWriter.java:199)
        at java.io.SequenceInputStream.read(SequenceInputStream.java:208)
        at java.io.SequenceInputStream.read(SequenceInputStream.java:211)
        at java.io.InputStream.read(InputStream.java:101)
        at com.sun.media.sound.WaveFileWriter.writeWaveFile(WaveFileWriter.java:247)
        at com.sun.media.sound.WaveFileWriter.write(WaveFileWriter.java:145)
        at javax.sound.sampled.AudioSystem.write(AudioSystem.java:1354)
        at audio1.NewClass.main(NewClass.java:33)

Can anyone help me what I am doing wrong?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
nullptr
  • 3,320
  • 7
  • 35
  • 68
  • There is existing java converter and it's source is [this]( http://code.google.com/p/mp3transform/source/browse/trunk/mp3/src/mp3/wav/WavConverter.java?r=6). May be your should just copy-paste source from it? – Daniil Dec 29 '12 at 22:09
  • I'd say the real problem is the source file. Try some of the MP3s available at my [media page](http://pscode.org/media/#sound). – Andrew Thompson Dec 30 '12 at 02:26
  • Could your MP3 have a variable bit rate? Maybe the media decoding code isn't that advanced – Jason Sperske Dec 30 '12 at 02:41
  • BTW (for "late comers"): Java does not support MP3 files anymore. – Apostolos Mar 02 '22 at 10:47

2 Answers2

11
public static byte [] getAudioDataBytes(byte [] sourceBytes, AudioFormat audioFormat) throws UnsupportedAudioFileException, IllegalArgumentException, Exception{
        if(sourceBytes == null || sourceBytes.length == 0 || audioFormat == null){
            throw new IllegalArgumentException("Illegal Argument passed to this method");
        }

        ByteArrayInputStream bais = null;
        ByteArrayOutputStream baos = null;
        AudioInputStream sourceAIS = null;
        AudioInputStream convert1AIS = null;
        AudioInputStream convert2AIS = null;

        try{
            bais = new ByteArrayInputStream(sourceBytes);
            sourceAIS = AudioSystem.getAudioInputStream(bais);
            AudioFormat sourceFormat = sourceAIS.getFormat();
            AudioFormat convertFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sourceFormat.getSampleRate(), 16, sourceFormat.getChannels(), sourceFormat.getChannels()*2, sourceFormat.getSampleRate(), false);
            convert1AIS = AudioSystem.getAudioInputStream(convertFormat, sourceAIS);
            convert2AIS = AudioSystem.getAudioInputStream(audioFormat, convert1AIS);

            baos = new ByteArrayOutputStream();

            byte [] buffer = new byte[8192];
            while(true){
                int readCount = convert2AIS.read(buffer, 0, buffer.length);
                if(readCount == -1){
                    break;
                }
                baos.write(buffer, 0, readCount);
            }
            return baos.toByteArray();
        } catch(UnsupportedAudioFileException uafe){
            //uafe.printStackTrace();
            throw uafe;
        } catch(IOException ioe){
            //ioe.printStackTrace();
            throw ioe;
        } catch(IllegalArgumentException iae){
            //iae.printStackTrace();
            throw iae;
        } catch (Exception e) {
            //e.printStackTrace();
            throw e;
        }finally{
            if(baos != null){
                try{
                    baos.close();
                }catch(Exception e){
                }
            }
            if(convert2AIS != null){
                try{
                    convert2AIS.close();
                }catch(Exception e){
                }
            }
            if(convert1AIS != null){
                try{
                    convert1AIS.close();
                }catch(Exception e){
                }
            }
            if(sourceAIS != null){
                try{
                    sourceAIS.close();
                }catch(Exception e){
                }
            }
            if(bais != null){
                try{
                    bais.close();
                }catch(Exception e){
                }
            }
        }
    }

Here sourceBytes represents MP3 file or WAV file. audioFormat is PCM format in which you want conversion. Also we need to put mp3spi.jar, tritonus_mp3.jar, jl*.jar, tritonus_share.jar from javazoom.com in classpath. Hope this may help to other.

Java 7 version:

public static byte [] getAudioDataBytes(byte [] sourceBytes, AudioFormat audioFormat) throws UnsupportedAudioFileException, IllegalArgumentException, Exception {
    if(sourceBytes == null || sourceBytes.length == 0 || audioFormat == null){
        throw new IllegalArgumentException("Illegal Argument passed to this method");
    }

    try (final ByteArrayInputStream bais = new ByteArrayInputStream(sourceBytes);
         final AudioInputStream sourceAIS = AudioSystem.getAudioInputStream(bais)) {
        AudioFormat sourceFormat = sourceAIS.getFormat();
        AudioFormat convertFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sourceFormat.getSampleRate(), 16, sourceFormat.getChannels(), sourceFormat.getChannels()*2, sourceFormat.getSampleRate(), false);
        try (final AudioInputStream convert1AIS = AudioSystem.getAudioInputStream(convertFormat, sourceAIS);
             final AudioInputStream convert2AIS = AudioSystem.getAudioInputStream(audioFormat, convert1AIS);
             final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte [] buffer = new byte[8192];
            while(true){
                int readCount = convert2AIS.read(buffer, 0, buffer.length);
                if(readCount == -1){
                    break;
                }
                baos.write(buffer, 0, readCount);
            }
            return baos.toByteArray();
        }
    }
}

Maven:

<dependency>
    <groupId>com.googlecode.soundlibs</groupId>
    <artifactId>mp3spi</artifactId>
    <version>1.9.5-1</version>
</dependency>
<dependency>
    <groupId>com.googlecode.soundlibs</groupId>
    <artifactId>jlayer</artifactId>
    <version>1.0.1-1</version>
    <exclusions>
        <exclusion>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </exclusion>
    </exclusions>
</dependency>
Hendy Irawan
  • 20,498
  • 11
  • 103
  • 114
nullptr
  • 3,320
  • 7
  • 35
  • 68
  • 2
    just a really good example on how awesome try-with-resources is :P. replace the whole closing stuff with a try(//instantiate Closeables;...;...;) { } catch(Ex...){}. and the code is a beauty. – Martin Braun Jan 13 '13 at 12:36
  • Not sure I understand this code. How are we specifying that the returned byte array will be data in the wav format? – IcedDante Jan 18 '17 at 23:10
  • 2
    I have tried the Java7 code and it breaks at ' final AudioInputStream convert2AIS = AudioSystem.getAudioInputStream(audioFormat, convert1AIS);' I am passing the target convertFormat from outside the function as 'new AudioFormat(Encoding.PCM_SIGNED, 16000, 16, 1, 2, 16000, true)' gives the same error 'java.lang.IllegalArgumentException: Unsupported conversion: MPEG1L3 44100.0 Hz, unknown bits per sample, mono, unknown frame size, 38.28125 frames/second, from PCM_SIGNED 16000.0 Hz, 16 bit, mono, 2 bytes/frame, big-endian' – user482963 Feb 08 '17 at 08:28
  • Same thing here, with an mp3 that can be played using the demo code from the mp3spi home page: http://www.javazoom.net/mp3spi/documents.html – Guillaume Sep 12 '17 at 21:19
-1

Note for "late comers": Java does not support MP3 files anymore, at least up to this date (March 2022). (For intellectual property reasons, etc.)

Apostolos
  • 3,115
  • 25
  • 28
  • Highly unlikely this is due to intellectual property reasons since MP3 patents have expired in US in 2017. – Andrew Kravchuk Jul 26 '22 at 05:07
  • A viable alternative for mp3plugin.jar in 2022 I've success with is ffsampledsp library: https://github.com/hendriks73/ffsampledsp – Andrew Kravchuk Jul 26 '22 at 05:29
  • Re "copyright": This is what I read somewhere --I don't have the reference anymore-- i,e, MP3 functionality was **removed** from Java for intellectual property reasons. I'm just the messenger ... – Apostolos Jul 27 '22 at 11:51
  • Re alternative for MP3: For a limited usage (hust a few times), the easiest way is to convert the MP3 to WAV and use AudioInputStream to open and play the file. Thanks for the suggestion anyway! – Apostolos Jul 27 '22 at 11:58