1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| import com.xuggle.mediatool.IMediaReader; import com.xuggle.mediatool.IMediaWriter; import com.xuggle.mediatool.ToolFactory; import com.xuggle.xuggler.ICodec; import com.xuggle.xuggler.IContainer; import com.xuggle.xuggler.IStream; import com.xuggle.xuggler.IStreamCoder;
public class VideoCompressor {
public static void main(String[] args) { if (args.length != 3) { System.err.println("用法: java VideoCompressor <输入文件> <输出文件> <目标比特率(kbps)>"); System.exit(1); }
String inputFile = args[0]; String outputFile = args[1]; int targetBitrate = Integer.parseInt(args[2]) * 1000;
try { compressVideo(inputFile, outputFile, targetBitrate); System.out.println("视频压缩完成: " + outputFile); } catch (Exception e) { System.err.println("压缩过程中发生错误: " + e.getMessage()); e.printStackTrace(); } }
public static void compressVideo(String inputFilePath, String outputFilePath, int targetBitrate) { IMediaReader reader = ToolFactory.makeReader(inputFilePath);
IMediaWriter writer = ToolFactory.makeWriter(outputFilePath, reader);
IContainer inputContainer = IContainer.make(); if (inputContainer.open(inputFilePath, IContainer.Type.READ, null) < 0) { throw new IllegalArgumentException("无法打开输入文件: " + inputFilePath); }
int videoStreamIndex = -1; IStreamCoder videoCoder = null; for (int i = 0; i < inputContainer.getNumStreams(); i++) { IStream stream = inputContainer.getStream(i); IStreamCoder coder = stream.getStreamCoder();
if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) { videoStreamIndex = i; videoCoder = coder; break; } }
if (videoStreamIndex == -1) { throw new RuntimeException("未找到视频流"); }
if (videoCoder.open() < 0) { throw new RuntimeException("无法打开视频编码器"); }
writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_H264, videoCoder.getWidth(), videoCoder.getHeight());
writer.getContainer().getStream(0).getStreamCoder().setBitRate(targetBitrate);
while (reader.readPacket() == null) ;
writer.close(); reader.close(); videoCoder.close(); } }
|