using OpenCvSharp; using NAudio.Wave; // 定义视频和音频的参数 int fps = 30; Size videoSize = new Size(640, 480); WaveFormat audioFormat = new WaveFormat(44100, 16, 2); // 创建视频编码器 VideoWriter videoWriter = new VideoWriter("output.avi", FourCC.XVID, fps, videoSize, true); // 创建音频录制器 WaveFileWriter audioWriter = new WaveFileWriter("audio.wav", audioFormat); // 创建视频捕获器 VideoCapture videoCapture = new VideoCapture(0); videoCapture.Set(CaptureProperty.FrameWidth, videoSize.Width); videoCapture.Set(CaptureProperty.FrameHeight, videoSize.Height); videoCapture.Set(CaptureProperty.Fps, fps); // 创建音频捕获器 WaveInEvent audioCapture = new WaveInEvent(); audioCapture.WaveFormat = audioFormat; audioCapture.DataAvailable += (sender, e) => { audioWriter.Write(e.Buffer, 0, e.BytesRecorded); }; // 开始录制音频和视频 videoWriter.Open(); videoCapture.Start(); audioCapture.StartRecording(); while (true) { Mat frame = new Mat(); videoCapture.Read(frame); if (frame.Empty()) break; videoWriter.Write(frame); Cv2.ImShow("video", frame); if (Cv2.WaitKey(1) == 27) break; } // 停止录制音频和视频 videoCapture.Release(); videoWriter.Release(); Cv2.DestroyAllWindows(); audioCapture.StopRecording(); audioWriter.Close(); audioWriter.Dispose(); // 合并音视频 var videoFile = new MediaFile { Filename = "output.avi" }; var audioFile = new MediaFile { Filename = "audio.wav" }; var outputFile = new MediaFile { Filename = "output.mp4" }; using (var engine = new Engine()) { engine.Convert(videoFile, audioFile, outputFile); }
首先定义了视频和音频的参数。然后创建了视频编码器和音频录制器,以便能够将视频和音频写入文件。接下来创建了视频和音频的捕获器,以便能够从摄像头和麦克风捕获图像和声音。 在主循环中不断从摄像头中读取图像,并将其写入视频文件中。同时通过OpenCVSharp的ImShow函数将图像显示在屏幕上。当用户按下ESC键时,程序退出主循环。 最后,我们停止录制音频和视频,并将它们合并成一个MP4文件。这里我们使用了FFmpeg的C#封装库FFmpeg.NET来进行音视频合并。
标签:视频,frame,C#,NAudio,录制,videoCapture,OpenCVSharp,new,音频 From: https://www.cnblogs.com/LuoCore/p/17241242.html