title: Convert mp3 to wav in Java
body: <p>I installed the mp3spi to support reading mp3 files in my Java 8 project usng the javax.sound* libraries. My goal now is to write mp3 to a wav file. However, the result is incorrect. Here's the code in its simplest format:</p>
  
  <pre><code>public static void mp3ToWav(InputStream mp3Data) throws UnsupportedAudioFileException, IOException {
      AudioInputStream mp3Stream = AudioSystem.getAudioInputStream(mp3Data);
      AudioFormat format = mp3Stream.getFormat();
      AudioFormat convertFormat = new AudioSystem.write(mp3Stream, Type.WAVE, new File("C:\\temp\\out.wav"));
  }
  </code></pre>
  
  <p>There's one other way as outlined here (<a href="https://stackoverflow.com/questions/14085199/mp3-to-wav-conversion-in-java">mp3 to wav conversion in java</a>):</p>
  
  <pre><code>File mp3 = new File("C:\\music\\greatest-songs-of-all-time\\RebeccaBlack-Friday.mp3");
  if(!mp3.exists()) {
      throw new FileNotFoundException("couldn't find mp3");
  }
  FileInputStream fis = new FileInputStream(mp3);
  BufferedInputStream bis = new BufferedInputStream(fis);
  
  AudioInputStream mp3Stream = AudioSystem.getAudioInputStream(bis);
  AudioFormat sourceFormat = mp3Stream.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(mp3Stream)) {
      final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      final AudioInputStream convert2AIS = AudioSystem.getAudioInputStream(convertFormat, convert1AIS);
      System.out.println("Length is: " + mp3Stream.getFrameLength() + " div by " + mp3Stream.getFormat().getFrameRate());
      byte [] buffer = new byte[8192];
      int iteration = 0;
      while(true){
          int readCount = convert2AIS.read(buffer, 0, buffer.length);
          if(readCount == -1){
              break;
          }
          baos.write(buffer, 0, readCount);
          iteration++;
      }
  
      System.out.println("completed with iteration: " + iteration);
  
      FileOutputStream fw = new FileOutputStream("C:\\temp\\out-2.wav");
      fw.write(baos.toByteArray());
      fw.close();
  }
  
  bis.close();
  fis.close();
  </code></pre>
  
  <p>This generates a file that's over 30 mb from a compressed mp3 of 4-5 mb, however it doesn't work as a valid WAV file.</p>
  
  <p>The method that does work for me involves using JLayer Converter class, however, because I want to do some other processing like cutting out portions of audio, modifying the volume and playback speed, etc., I feel like I might be better off working with the native library.</p>