mp3 to wav conversion in java

29,001
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>
Share:
29,001
nullptr
Author by

nullptr

Updated on October 05, 2020

Comments

  • nullptr
    nullptr over 3 years

    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?

  • Martin Braun
    Martin Braun over 11 years
    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.
  • IcedDante
    IcedDante over 7 years
    Not sure I understand this code. How are we specifying that the returned byte array will be data in the wav format?
  • user482963
    user482963 over 7 years
    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'
  • Guillaume
    Guillaume over 6 years
    Same thing here, with an mp3 that can be played using the demo code from the mp3spi home page: javazoom.net/mp3spi/documents.html