C#實現語音視頻錄製 【基於MCapture + MFile】

在上一篇使用C#採集語音視頻、屏幕桌面【基於MCapture組件】的文章中,我們已經可以採集到語音、視頻、桌面數據了,那麼,接下來我們再結合MFile的錄製功能,便能把這些數據寫到文件中,生成標準的mp4文件。

        使用MCapture+MFile,我們可以實現以下類似的應用:

(1)錄製課件:錄製屏幕桌面+語音。

(2)錄製自己的MV:錄製攝像頭視頻+語音。

(3)錄製教學視頻:錄製桌面+自己的視頻+語音。(其中將桌面與自己視頻疊加在一起)

那接下來這篇文章將詳細介紹應用(2)的實現,我們做一個簡單的Demo(文末有源碼下載)。另外兩種應用都可以在本文Demo的基礎上作一些修改即可。Demo 運行的截圖如下所示:      

      

         首先,當點擊啓動設備按鈕時,我們創建一個攝像頭採集器實例和一個麥克風採集器實例,並啓動它們開始採集: 

複製代碼
    this.cameraCapturer = CapturerFactory.CreateCameraCapturer(0, new Size(int.Parse(this.textBox_width.Text), int.Parse(this.textBox_height.Text)), this.fps);
    this.cameraCapturer.ImageCaptured += new CbGeneric<Bitmap>(cameraCapturer_ImageCaptured);
    this.cameraCapturer.CaptureError += new CbGeneric<Exception>(cameraCapturer_CaptureError);
    this.microphoneCapturer = CapturerFactory.CreateMicrophoneCapturer(0);
    this.microphoneCapturer.AudioCaptured += new CbGeneric<byte[]>(microphoneCapturer_AudioCaptured);
    this.microphoneCapturer.CaptureError += new CbGeneric<Exception>(microphoneCapturer_CaptureError);
    //開始採集
    this.cameraCapturer.Start();
    this.microphoneCapturer.Start();
複製代碼

       接下來,點擊開始錄製按鈕時,我們初始化VideoFileMaker組件:

    this.videoFileMaker = new VideoFileMaker();
    this.videoFileMaker.AutoDisposeVideoFrame = true;
    this.videoFileMaker.Initialize("test.mp4", VideoCodecType.H264, int.Parse(this.textBox_width.Text), int.Parse(this.textBox_height.Text), this.fps, AudioCodecType.AAC, 16000, 1, true);
    this.isRecording = true;

      參數中設定,使用h.264對視頻進行編碼,使用aac對音頻進行編碼,並生成mp4格式的文件。然後,我們可以通過OMCS獲取實時的音頻數據和視頻數據,並將它們寫到文件中。

複製代碼
    void microphoneCapturer_AudioCaptured(byte[] audioData) //採集到的語音數據
    {
        if (this.isRecording)
        {
            this.videoFileMaker.AddAudioFrame(audioData);           
        }
    }
    //採集到的視頻圖像
    void cameraCapturer_ImageCaptured(Bitmap img)
    {
        if (this.isRecording)
        {
            this.DisplayVideo((Bitmap)img.Clone());
            this.videoFileMaker.AddVideoFrame(img);           
        }
        else
        {
            this.DisplayVideo(img);
        }
    }
複製代碼

     當想結束錄製時,則調用Close方法:

   this.videoFileMaker.Close(true);

 更多細節大家可以下載文末的源碼研究,最後,有幾點需要額外強調一下的:

(1)攝像頭採集的幀頻最好與錄製所設定的幀頻完全一致。demo中是使用成員變量fps來表示的。

(2)videoFileMaker的AutoDisposeVideoFrame屬性要設置爲ture,即儘快釋放不再使用的視頻幀,節省內存。

(3)DisplayVideo方法使用的是採集視頻幀的複製品,這是因爲videoFileMaker不是同步寫入的,而是先將幀放入隊列,然後異步寫入的。

(4)DisplayVideo方法在使用完作爲背景的視頻幀後,也要儘快釋放。道理同上。


Demo源碼下載

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章