简体   繁体   中英

Converting mp3 to wav in Java

I'm writing a generalized utility for converting audio files to WAV. Works ok for WAV to WAV (I'm also changing some of the attributes), but I can't convert MP3 files. I have mp3spi in my classpath, so it seems to be able to read the MP3, but the WAV file that gets written doesn't seem to work.

In this example, I'm not trying to change any properties. Just reading the MP3 and writing to a WAV file

My code looks something like this

    File inputFileObj = new File(input);
    AudioInputStream audioInputStream = null;

    try {
        audioInputStream = AudioSystem.getAudioInputStream(inputFileObj);
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("Input file format:");
    System.out.println(AudioSystem.getAudioFileFormat(inputFileObj));

    try {
        AudioSystem.write(audioInputStream, outputType, new File(output));
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("Output file format:");
    System.out.println(AudioSystem.getAudioFileFormat(new File(output)));

Here's the output. As you can see, it appears to write the output file, but when I try to retrieve the format of the output file, it can't handle it. And if I try to play the output file, the player doesn't recognize it.

Input file: c:\testfiles\sample-b-converted.mp3
Output file: c:\testfiles\foo.wav
Output type: wav

Input file format:
MP3 (.mp3) file, byte length: 13227300, data format: MPEG2L3 16000.0 Hz, unknown bits per sample, mono, unknown frame size, 27.777779 frames/second, , frame length: 122475
Bytes written: 13227344
Output file format:
Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: file is not a supported file type
    at javax.sound.sampled.AudioSystem.getAudioFileFormat(AudioSystem.java:1078)
    at org.torchai.AudioFileConvert01.main(AudioFileConvert01.java:60)

Is there something else I need to get this working?

Someone posted a comment referring me to mp3 to wav conversion in java . I had seen this issue, but didn't quite see the main aspect of the answer, since it wasn't really explained well.

An MP3 file apparently needs to go through a 2-step conversion. I don't fully understand why, but it seems you must first convert it to PCM_SIGNED with a sample size of 16 and a framesize of 2*# of channels. At that point, you can convert it again to the final format that you want.

Would still love to have a better explanation, but this at least gets me past my issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM