Java 使用JMF将多路复用音频/视频录制到文件
我有一个使用JMF的项目,在短时间内(几秒钟到几分钟)记录网络摄像机和音频输入,然后将结果写入文件 我的项目的问题是,该文件从未正确生成,无法播放 虽然我已经找到了许多例子,说明如何通过RTP进行音频和视频的多路传输,或者如何将输入文件从一种格式转换为另一种格式,但我还没有看到一个可以捕获音频和视频并将其写入文件的工作示例Java 使用JMF将多路复用音频/视频录制到文件,java,media,video-capture,jmf,multiplexing,Java,Media,Video Capture,Jmf,Multiplexing,我有一个使用JMF的项目,在短时间内(几秒钟到几分钟)记录网络摄像机和音频输入,然后将结果写入文件 我的项目的问题是,该文件从未正确生成,无法播放 虽然我已经找到了许多例子,说明如何通过RTP进行音频和视频的多路传输,或者如何将输入文件从一种格式转换为另一种格式,但我还没有看到一个可以捕获音频和视频并将其写入文件的工作示例 有没有人有这样做的功能代码示例?我找到了无法在JMF下从两个单独的捕获设备生成文件的原因,这与启动命令的顺序有关。特别是,处理器将获取数据源,或合并数据源,分配和同步时基,并
有没有人有这样做的功能代码示例?我找到了无法在JMF下从两个单独的捕获设备生成文件的原因,这与启动命令的顺序有关。特别是,处理器将获取数据源,或合并数据源,分配和同步时基,并为您启动/停止数据源,因此我试图手动启动数据源所做的额外工作是完全多余的,并且会给工作带来麻烦 这是一个痛苦的尝试和错误,我建议您阅读每一行代码,了解顺序,了解包含了什么,遗漏了什么以及为什么,然后再尝试自己实现它。如果你不小心的话,JMF就是一只熊 哦,记住捕捉异常。由于长度限制,我不得不省略该代码 以下是我的最终解决方案:
public void doRecordingDemo() {
// Get the default media capture device for audio and video
DataSource[] sources = new DataSource[2];
sources[0] = Manager.createDataSource(audioDevice.getLocator());
sources[1] = Manager.createDataSource(videoDevice.getLocator());
// Merge the audio and video streams
DataSource source = Manager.createMergingDataSource(sources);
// Create a processor to convert from raw format to a file format
// Notice that we are NOT starting the datasources, but letting the
// processor take care of this for us.
Processor processor = Manager.createProcessor(source);
// Need a configured processor for this next step
processor.configure();
waitForState(processor, Processor.Configured);
// Modify this to suit your needs, but pay attention to what formats can go in what containers
processor.setContentDescriptor(new FileTypeDescriptor(FileTypeDescriptor.QUICKTIME));
// Use the processor to convert the audio and video into reasonable formats and sizes
// There are probably better ways to do this, but you should NOT make any assumptions
// about what formats are supported, and instead use a generic method of checking the
// available formats and sizes. You have been warned!
for (TrackControl control : processor.getTrackControls()) {
if (control.getFormat() instanceof VideoFormat || control.getFormat() instanceof AudioFormat) {
if (control.getFormat() instanceof AudioFormat) {
// In general, this is safe for audio, but do not make assumptions for video.
// Things get a little wonky for video because of how complex the options are.
control.setFormat(new AudioFormat(AudioFormat.GSM));
}
if (control.getFormat() instanceof VideoFormat) {
VideoFormat desiredVideoFormat = null;
Dimension targetDimension = new Dimension(352, 288);
// Search sequentially through this array of formats
VideoFormat[] desiredFormats = new VideoFormat[] {new H263Format(), new JPEGFormat(), new RGBFormat(), new YUVFormat()};
for (VideoFormat checkFormat : desiredFormats) {
// Search the video formats looking for a match.
List<VideoFormat> candidates = new LinkedList<VideoFormat>();
for (Format format : control.getSupportedFormats()) {
if (format.isSameEncoding(checkFormat)) {
candidates.add((VideoFormat) format);
}
}
if (!candidates.isEmpty()) {
// Get the first candidate for now since we have at least a format match
desiredVideoFormat = candidates.get(0);
for (VideoFormat format : candidates) {
if (targetDimension.equals(format.getSize())) {
// Found exactly what we're looking for
desiredVideoFormat = format;
break;
}
}
}
if (desiredVideoFormat != null) {
// If we found a match, stop searching formats
break;
}
}
if (desiredVideoFormat != null) {
// It's entirely possible (but not likely) that we got here without a format
// selected, so this null check is unfortunately necessary.
control.setFormat(desiredVideoFormat);
}
}
control.setEnabled(true);
System.out.println("Enabled track: " + control + " (" + control.getFormat() + ")");
}
}
// To get the output from a processor, we need it to be realized.
processor.realize();
waitForState(processor, Processor.Realized);
// Get the data output so we can output it to a file.
DataSource dataOutput = processor.getDataOutput();
// Create a file to receive the media
File answerFile = new File("recording.mov");
MediaLocator dest = new MediaLocator(answerFile.toURI().toURL());
// Create a data sink to write to the disk
DataSink answerSink = Manager.createDataSink(dataOutput, dest);
// Start the processor spinning
processor.start();
// Open the file
answerSink.open();
// Start writing data
answerSink.start();
// SUCCESS! We are now recording
Thread.sleep(10000); // Wait for 10 seconds so we record 10 seconds of video
try {
// Stop the processor. This will also stop and close the datasources
processor.stop();
processor.close();
try {
// Let the buffer run dry. Event Listeners never seem to get called,
// so this seems to be the most effective way.
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
try {
// Stop recording to the file.
answerSink.stop();
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
} finally {
try {
// Whatever else we do, close the file if we can to avoid leaking.
answerSink.close();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
try {
// Deallocate the native processor resources.
processor.deallocate();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
// My little utility function to wait for a given state.
private void waitForState(Player player, int state) {
// Fast abort
if (player.getState() == state) {
return;
}
long startTime = new Date().getTime();
long timeout = 10 * 1000;
final Object waitListener = new Object();
ControllerListener cl = new ControllerListener() {
@Override
public void controllerUpdate(ControllerEvent ce) {
synchronized (waitListener) {
waitListener.notifyAll();
}
}
};
try {
player.addControllerListener(cl);
// Make sure we wake up every 500ms to check for timeouts and in case we miss a signal
synchronized (waitListener) {
while (player.getState() != state && new Date().getTime() - startTime < timeout) {
try {
waitListener.wait(500);
} catch (InterruptedException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
} finally {
// No matter what else happens, we want to remove this
player.removeControllerListener(cl);
}
}
public void doRecordingDemo(){
//获取音频和视频的默认媒体捕获设备
DataSource[]sources=新数据源[2];
sources[0]=Manager.createDataSource(audioDevice.getLocator());
sources[1]=Manager.createDataSource(videoDevice.getLocator());
//合并音频和视频流
DataSource source=Manager.createMergingDataSource(源);
//创建从原始格式转换为文件格式的处理器
//请注意,我们不是启动数据源,而是让
//处理器替我们处理这个。
Processor=Manager.createProcessor(源);
//需要为下一步配置处理器
processor.configure();
waitForState(处理器,处理器。已配置);
//修改此项以满足您的需要,但请注意哪些格式可以放在哪些容器中
processor.setContentDescriptor(新的FileTypeDescriptor(FileTypeDescriptor.QUICKTIME));
//使用处理器将音频和视频转换为合理的格式和大小
//也许有更好的方法可以做到这一点,但你不应该做任何假设
//关于支持哪些格式,而是使用常规方法检查
//可用的格式和大小。已警告您!
for(TrackControl:processor.getTrackControls()){
if(control.getFormat()instanceof VideoFormat | | control.getFormat()instanceof AudioFormat){
if(control.getFormat()instanceof AudioFormat){
//一般来说,这对音频是安全的,但不要对视频进行假设。
//对于视频来说,事情变得有点不稳定,因为选项有多复杂。
控件.setFormat(新的AudioFormat(AudioFormat.GSM));
}
if(control.getFormat()实例为VideoFormat){
VideoFormat desiredVideoFormat=null;
维度targetDimension=新维度(352288);
//按顺序搜索此格式数组
VideoFormat[]desiredFormats=新的VideoFormat[]{new H263Format(),new JPEGFormat(),new RGBFormat(),new YUVFormat()};
for(视频格式检查格式:desiredFormats){
//搜索视频格式以查找匹配项。
列表候选项=新建LinkedList();
for(格式:control.getSupportedFormats()){
if(format.isSameEncoding(checkFormat)){
候选人。添加((视频格式)格式);
}
}
如果(!candidates.isEmpty()){
//因为我们至少有一个格式匹配,所以现在获取第一个候选
desiredVideoFormat=candidates.get(0);
适用于(视频格式:候选人){
if(targetDimension.equals(format.getSize())){
//找到了我们要找的东西
desiredVideoFormat=格式;
打破
}
}
}
if(desiredVideoFormat!=null){
//如果找到匹配项,请停止搜索格式
打破
}
}
if(desiredVideoFormat!=null){
//我们完全有可能(但不太可能)在没有格式的情况下来到这里
//已选中,因此很遗憾,此空检查是必需的。
控件.setFormat(desiredVideoFormat);
}
}
control.setEnabled(true);
System.out.println(“启用的曲目:“+control+”(“+control.getFormat()+”));
}
}
//要从处理器获得输出,我们需要实现它。
processor.realize();
waitForState(处理器,处理器,已实现);
//获取数据输出,以便将其输出到文件。
DataSource dataOutput=processor.getDataOutput();
//创建一个文件