Audio converting with Xuggler

后端 未结 3 1536
生来不讨喜
生来不讨喜 2021-02-11 00:05

I\'m trying to convert aac/wav/wma audio files to mp3 with Xuggler in Java.

Unfortunately, I have a big loss of quality. My input file size is about 7MB and my output fi

3条回答
  •  长情又很酷
    2021-02-11 01:04

    I'll do something like this:

    public void convertToMP3(File input, File output, int kbps) { //modify on your convenience
        // create a media reader
        IMediaReader mediaReader = ToolFactory.makeReader(input.getPath());
    
        // create a media writer
        IMediaWriter mediaWriter = ToolFactory.makeWriter(output.getPath(), mediaReader);
    
        // add a writer to the reader, to create the output file
        mediaReader.addListener(mediaWriter);
    
        // add a IMediaListner to the writer to change bit rate
        mediaWriter.addListener(new MediaListenerAdapter() {
            @Override
            public void onAddStream(IAddStreamEvent event) {
                IStreamCoder streamCoder = event.getSource().getContainer().getStream(event.getStreamIndex()).getStreamCoder();
                streamCoder.setFlag(IStreamCoder.Flags.FLAG_QSCALE, false);
                streamCoder.setBitRate(kbps);
                streamCoder.setBitRateTolerance(0);
                }
            });
    
        // read and decode packets from the source file and
        // and dispatch decoded audio and video to the writer
        while (mediaReader.readPacket() == null);
    }
    

    input is the File (aac/wav/wma) you want to convert and output is a new .mp3 file (Xuggler figure out the conversion by the extension).

    You can increase the quality increasing kbps (i.e. for 320 kbps you need to pass in 320000).

    Hope that helps :-)

    FYI: for Java projects you'll need to import the following if you haven't already done so:

    import com.xuggle.mediatool.MediaListenerAdapter;
    import com.xuggle.mediatool.event.IAddStreamEvent;
    import com.xuggle.xuggler.IStreamCoder;
    

提交回复
热议问题