聲卡錄製是一個常見的需求,比如我們在線觀看視頻或聽歌,覺得一段音樂特別好,但是,又沒有提供下載,那麼,我們就可以使用聲卡錄製技術,邊播放邊將其錄製下來。
實現聲卡錄製,涉及到兩個基礎的技術:聲卡捕捉、錄製聲音成mp3文件。語音視頻採集組件MCapture提供了聲卡採集的功能,而語音視頻錄製組件MFile提供了將聲音數據錄製生成mp3文件的功能。所以,結合 MCapture 和 MFile ,將它們組合起來,就可以實現我們想要的軟件。
本文實現了一個簡單的聲卡錄製的Demo,Demo運行起來後的截圖如下:
停止錄製後,將在運行目錄下生成一個名爲 test.mp3 的文件,然後,我們可以使用各種播放器(如QQ音樂播放器)來播放它。下面,我們來看這個Demo的詳細實現。
private ISoundcardCapturer soundcardCapturer;
private AudioFileMaker audioFileMaker;
private volatile bool isRecording = false;
//開始聲卡採集、錄製
private void button1_Click(object sender, EventArgs e)
{
try
{
//根據聲卡採集器 【目前聲卡採集僅支持vista以及以上系統】
this.soundcardCapturer = CapturerFactory.CreateSoundcardCapturer();
this.soundcardCapturer.AudioCaptured += new ESBasic.CbGeneric<byte[]>(soundcardCapturer_AudioCaptured);
this.soundcardCapturer.CaptureError += new CbGeneric<Exception>(microphoneCapturer_CaptureError);
//開始採集聲卡
this.soundcardCapturer.Start();
this.audioCount = 0;
this.audioFileMaker = new AudioFileMaker();
this.audioFileMaker.Initialize("test.mp3",AudioCodecType.MP3, this.soundcardCapturer.SampleRate, this.soundcardCapturer.ChannelCount);
this.isRecording = true;
this.button_startRecord.Enabled = false;
this.button_stopRecord.Enabled = true;
this.label_recording.Visible = true;
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
//停止聲卡採集、停止錄製
private void button2_Click(object sender, EventArgs e)
{
try
{
this.Cursor = Cursors.WaitCursor;
CbGeneric cb = new CbGeneric(this.StopRecordAsyn);
cb.BeginInvoke(null, null);
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
private void StopRecordAsyn()
{
this.isRecording = false;
this.soundcardCapturer.Stop();
this.soundcardCapturer.Dispose(); //必須要釋放聲卡採集器!!!!!!!!
this.audioFileMaker.Close(true);
this.audioFileMaker.Dispose();
this.audioFileMaker = null;
this.AfterStopRecord();
}
private void AfterStopRecord()
{
if (this.InvokeRequired)
{
this.BeginInvoke(new CbGeneric(this.AfterStopRecord));
}
else
{
this.button_startRecord.Enabled = true;
this.button_stopRecord.Enabled = false;
this.label_recording.Visible = false;
this.Cursor = Cursors.Default;
MessageBox.Show("錄製完成!" + (this.audioCount * 0.05).ToString() + "秒。");
}
}
private int audioCount = 0;
void soundcardCapturer_AudioCaptured(byte[] audioData) //採集到的語音數據
{
if (this.isRecording)
{
this.audioFileMaker.AddAudioFrame(audioData);
++this.audioCount;
}
}
void microphoneCapturer_CaptureError(Exception obj)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (this.isRecording)
{
MessageBox.Show("正在錄製視頻,請先停止!");
e.Cancel = true;
return;
}
}
對於一般的機器而言,MCapture採集聲卡得到的音頻數據的基本信息是這樣的:
(1)bit位數:16
(2)聲道數:2
(3)採樣率:48000
(4)MCapture每隔50毫秒觸發一次AudioCaptured事件。
要特別注意:在初始化MFile的AudioFileMaker的時候(即調用其Initialize方法),傳入的採樣率和聲道數,必須使用ISoundcardCapturer的SampleRate和ChannelCount屬性。
下載聲卡錄製Demo的源碼:RecordSoundCardDemo.rar