声卡录制是一个常见的需求,比如我们在线观看视频或听歌,觉得一段音乐特别好,但是,又没有提供下载,那么,我们就可以使用声卡录制技术,边播放边将其录制下来。
实现声卡录制,涉及到两个基础的技术:声卡捕捉、录制声音成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