以前寫過兩篇錄制麥克風語音和攝像頭視頻的文章(實現語音視頻錄制、在服務器端錄制語音視頻),最近有朋友問,如果要實現屏幕錄制這樣的功能,該怎麼做了?實際上原理是差不多的,如果了解了我前面兩篇文章中介紹的內容,只要在它們的基礎上做一些修改就可以了。 一.實現原理 實現方案仍然基於OMCS+MFile構建,原理與實現語音視頻錄制差不多,我這裡只列出其中的主要差異: (1)使用DynamicDesktopConnector連接到屏幕桌面。 (2)使用定時器(比如10fps,則每隔100ms一次)定時調用DynamicDesktopConnector的GetCurrentImage方法,把得到的圖像使用MFile寫入視頻文件。 (3)Demo演示的是不需要同時錄制麥克風的聲音,所以使用了MFile提供的SilenceVideoFileMaker組件(而非原來的VideoFileMaker組件),僅僅錄制視頻數據。 (4)通過MultimediaManager的DesktopEncodeQuality屬性,控制屏幕圖像的清晰度。 二.實現代碼 該Demo的所有源碼如下所示,如果不想下載Demo,可以直接通過下面的代碼了解詳細的實現思路。 復制代碼 public partial class Form1 : Form { private MultimediaServer server; //在本地內嵌OMCS服務器 private IMultimediaManager multimediaManager; private SilenceVideoFileMaker maker = new SilenceVideoFileMaker(); //錄制無聲視頻 private DynamicDesktopConnector dynamicDesktopConnector = new DynamicDesktopConnector(); //遠程桌面連接器 public Form1() { InitializeComponent(); int port = 9900; OMCSConfiguration config = new OMCSConfiguration(10,8, EncodingQuality.High,16000,640,480,"") ; this.server = new MultimediaServer(port, new DefaultUserVerifier(), config, false, null); this.multimediaManager = MultimediaManagerFactory.GetSingleton(); this.multimediaManager.DesktopEncodeQuality = 1; //通過此參數控制清晰度 this.multimediaManager.Initialize("aa01", "", "127.0.0.1", port); this.dynamicDesktopConnector.ConnectEnded += new ESBasic.CbGeneric<ConnectResult>(dynamicDesktopConnector_ConnectEnded); this.dynamicDesktopConnector.BeginConnect("aa01"); //連接本地桌面 this.Cursor = Cursors.WaitCursor; } void dynamicDesktopConnector_ConnectEnded(ConnectResult obj) { System.Threading.Thread.Sleep(500); this.Ready(); } private void Ready() { if (this.InvokeRequired) { this.BeginInvoke(new CbGeneric(this.Ready)); } else { this.Cursor = Cursors.Default; this.button1.Enabled = true; this.label1.Visible = false; } } private System.Threading.Timer timer; private void button1_Click(object sender, EventArgs e) { try { Oraycn.MFile.GlobalUtil.SetAuthorizedUser("FreeUser", ""); //初始化H264視頻文件 this.maker.Initialize("test.mp4", VideoCodecType.H264, this.dynamicDesktopConnector.DesktopSize.Width, this.dynamicDesktopConnector.DesktopSize.Height, 10); this.timer = new System.Threading.Timer(new System.Threading.TimerCallback(this.Callback), null ,0, 100); this.label1.Text = "正在錄制......"; this.label1.Visible = true; this.button1.Enabled = false; this.button2.Enabled = true; } catch (Exception ee) { MessageBox.Show(ee.Message); } } //定時獲取屏幕圖像,並使用MFile寫入視頻文件 private void Callback(object state) { Bitmap bm = this.dynamicDesktopConnector.GetCurrentImage(); this.maker.AddVideoFrame(bm); } private void button2_Click(object sender, EventArgs e) { this.timer.Dispose(); this.button1.Enabled = false; this.button2.Enabled = false; this.label1.Visible = false; this.maker.Close(true); MessageBox.Show("生成視頻文件成功!"); } }