这是一篇旧帖子,但是,我希望我的回答对某人有所帮助:
我使用的代码与有问题的代码相同,但由于无法使用该代码转换某些文件,我遇到了麻烦。
在这个答案中,我打开文件,当它包含音频时,我创建文件。否则不会创建文件。这种方式是提取任何文件的音频部分的正确方法。
相同的模式可以应用于视频。我想我认为这段代码也会给出这个想法。
package test.video;
import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.IMediaWriter;
import com.xuggle.mediatool.MediaToolAdapter;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.mediatool.event.IAudioSamplesEvent;
import com.xuggle.mediatool.event.ICloseEvent;
import com.xuggle.mediatool.event.IOpenCoderEvent;
import com.xuggle.xuggler.IContainer;
import com.xuggle.xuggler.IStreamCoder;
/**
*
* @author Pasban
*/
public class separateAudioVideo {
public static void main(String[] args) throws Exception {
String file = "pasban/22.mp4";
String to = "pasban/22.mp3";
convert(file, to);
}
public static void convert(String from, final String to) {
IMediaReader mediaReader = ToolFactory.makeReader(from);
final int mySampleRate = 44100;
final int myChannels = 2;
mediaReader.addListener(new MediaToolAdapter() {
private IContainer container;
private IMediaWriter mediaWriter;
@Override
public void onOpenCoder(IOpenCoderEvent event) {
container = event.getSource().getContainer();
mediaWriter = null;
}
@Override
public void onAudioSamples(IAudioSamplesEvent event) {
if (container != null) {
if (mediaWriter == null) {
mediaWriter = ToolFactory.makeWriter(to);
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(128);
streamCoder.setChannels(myChannels);
streamCoder.setSampleRate(mySampleRate);
streamCoder.setBitRateTolerance(0);
}
});
mediaWriter.addAudioStream(0, 0, myChannels, mySampleRate);
}
mediaWriter.encodeAudio(0, event.getAudioSamples());
//System.out.println(event.getTimeStamp() / 1000);
}
}
@Override
public void onClose(ICloseEvent event) {
if (mediaWriter != null) {
mediaWriter.close();
}
}
});
while (mediaReader.readPacket() == null) {
}
}
}