Java Sound API MP3编码失败

时间:2015-05-23 15:23:27

标签: java audio mp3

我尝试使用Java Sound API编码wav文件,但会发生以下异常:

exception: java.lang.IllegalArgumentException: Unsupported conversion: MPEG1L3 from PCM_SIGNED 48000.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian

通过Maven我提供了以下依赖关系,比如MP3 SPI。

    <dependency>
        <groupId>com.googlecode.soundlibs</groupId>
        <artifactId>tritonus-share</artifactId>
        <version>LATEST</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>com.googlecode.soundlibs</groupId>
        <artifactId>mp3spi</artifactId>
        <version>LATEST</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>com.googlecode.soundlibs</groupId>
        <artifactId>vorbisspi</artifactId>
        <version>LATEST</version>
        <scope>compile</scope>
    </dependency>

目前,根据几个在线资源,我尝试使用以下方式/代码将wav文件编码为mp3:

private final AudioFormat.Encoding MPEG1L3 = new AudioFormat.Encoding("MPEG1L3");
private final AudioFileFormat.Type MP3 = new AudioFileFormat.Type("MP3", "mp3");

public void play() {

    try {

        // Get Audio Stream
        AudioInputStream inputStream = AudioSystem.getAudioInputStream(
                new BufferedInputStream(Files.newInputStream(Paths.get("input.wav")))
        );

        inputStream = getConvertedStream(inputStream, MPEG1L3);

        AudioSystem.write(inputStream, this.MP3, new File("out.mp3"));

    } catch(Exception exception) {
        exception.printStackTrace();
    }


}


private AudioInputStream getConvertedStream(
        AudioInputStream sourceStream,
        AudioFormat.Encoding targetEncoding) throws Exception {

    AudioFormat sourceFormat = sourceStream.getFormat();

    logger.info("Input format: " + sourceFormat);

    AudioInputStream targetStream = null;
    if (!AudioSystem.isConversionSupported(targetEncoding, sourceFormat)) {

        AudioFormat intermediateFormat = new AudioFormat(
                AudioFormat.Encoding.PCM_SIGNED,
                sourceFormat.getSampleRate(),
                16,
                sourceFormat.getChannels(),
                2 * sourceFormat.getChannels(), // frameSize
                sourceFormat.getSampleRate(),
                false);

        if (AudioSystem.isConversionSupported(intermediateFormat, sourceFormat)) {
            sourceStream = AudioSystem.getAudioInputStream(intermediateFormat, sourceStream);
        }
    }

    return AudioSystem.getAudioInputStream(targetEncoding, sourceStream);
}

我希望得到答案,为什么它不起作用! :(

0 个答案:

没有答案