none
c# 程序能否通过 AForge录制摄像头视频的同时录音? RRS feed

答案

  • 你好,

    你可以创建一个winform应用程序来实现录制视频时同时录音。

    首先,你需要添加以下nuget包。

    Accord
    Accord.Video
    Accord.Video.FFMPEG
    Aforge
    AForge.Math
    AForge.Video
    AForge.Video.DirectShow
    Aforge.Imaging
    Newtonsoft.Json

    其次,你需要添加一个combobox,两个button,一个  VideoSourcePlayer

    最后,你可以尝试下面的代码来完成录屏时录音。

      public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                this.FormBorderStyle = FormBorderStyle.FixedSingle;
                this.MaximizeBox = false;
            }
          
            private FilterInfoCollection videoDevices;
            private VideoCaptureDevice videoSource;
            private VideoFileWriter writer;
            private System.Timers.Timer myTimer;
            private int Indexof = 0;
    
            public VideoSourcePlayer VSP
            {
                get { return videoSourcePlayer1; }
            }
    
    
            [DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)]
            public static extern int mciSendString(
                string lpstrCommand,
                string lpstrReturnString,
                int uReturnLength,
                int hwndCallback
            );
    
            private void btRecord_Click(object sender, EventArgs e)
            {
                if (btRecord.Text == "Record")
                {
                    int videoBitRate = 1920 * 1080;
                    try
                    {
                        int width = videoSource.VideoCapabilities[9].FrameSize.Width;
                        int height = videoSource.VideoCapabilities[9].FrameSize.Height;
                        writer.Open("temp.wmv", width, height, 64, VideoCodec.WMV1, videoBitRate);
                        myTimer.Enabled = true;
                        myTimer.Start();
                        mciSendString("open new type WAVEAudio alias recsound", "", 0, 0);
                        mciSendString("record recsound", "", 0, 0);
                        btRecord.Text = "Stop";
                        btConnect.Enabled = false;
                    }
                    catch
                    {
                        MessageBox.Show("Please open camera!");
                    }
                }
                else if (btRecord.Text == "Stop")
                {
                    myTimer.Stop();
                    myTimer.Enabled = false;
                    mciSendString("stop recsound", "", 0, 0);
                    mciSendString("save recsound temp.wav", "", 0, 0);
                    mciSendString("close recsound", "", 0, 0);
                    btRecord.Text = "Record";
                    btConnect.Enabled = true;
                    System.Diagnostics.Process exep = new System.Diagnostics.Process();
                    exep.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + @"ffmpeg.exe";
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Video File|*.mkv";
                    sfd.FileName = "Untitled.mkv";
                    sfd.AddExtension = true;
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        if (System.IO.File.Exists(sfd.FileName))
                        {
                            System.IO.File.Delete(sfd.FileName);
                        }
                        exep.StartInfo.Arguments = "-i temp.wmv -i temp.wav -c copy " + sfd.FileName;
                    }
                    exep.StartInfo.CreateNoWindow = true;
                    exep.StartInfo.UseShellExecute = false;
                    exep.Start();
                }
            }
    
            private void btConnect_Click(object sender, EventArgs e)
            {
                if (btConnect.Text == "Connect")
                {
                    Indexof = Cameralist.SelectedIndex;
                    if (Indexof < 0)
                    {
                        MessageBox.Show("Please select a camera!");
                        return;
                    }
                    videoSource = new VideoCaptureDevice(videoDevices[Indexof].MonikerString);
                    videoSource.VideoResolution = videoSource.VideoCapabilities[9];
                    videoSourcePlayer1.VideoSource = videoSource;
                    videoSourcePlayer1.Start();
                    btConnect.Text = "Disconnect";
                    btRecord.Enabled = true;
                }
                else if (btConnect.Text == "Disconnect")
                {
                    videoSourcePlayer1.Stop();
                    btConnect.Text = "Connect";
                    btRecord.Enabled = false;
                 
                }
            }
    
            // Get camera list
            private void Camlist()
            {
                Cameralist.Items.Clear();
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
    
                if (videoDevices.Count == 0)
                {
                    MessageBox.Show("No camera found!");
                    return;
                }
                foreach (FilterInfo device in videoDevices)
                {
                    if (device.Name != "screen-capture-recorder")
                        Cameralist.Items.Add(device.Name);
                }
                Cameralist.SelectedIndex = 0;
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                myTimer = new System.Timers.Timer(10);
                myTimer.SynchronizingObject = this;
                myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
                myTimer.AutoReset = true;
                Camlist();
                writer = new VideoFileWriter();
                btRecord.Enabled = false;
            }
    
            private void myTimer_Elapsed(object sender, ElapsedEventArgs e)
            {
                if (videoSource == null)
                {
                    MessageBox.Show("Please open camera first!");
                    return;
                }
                //videoSourcePlayer继承Control父类,定义 GetCurrentVideoFrame能输出bitmap
                Bitmap bitmap = videoSourcePlayer1.GetCurrentVideoFrame();
                try
                {
                    writer.WriteVideoFrame(bitmap);
                }
                catch { } // 录制一半退出
            }
    
            private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            {
                videoSourcePlayer1.Stop();
            }
    
        
    
            public string ImgToBase64String(Bitmap bitmap)
            {
                try
                {
                    MemoryStream ms = new MemoryStream();
                    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    byte[] arr = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(arr, 0, (int)ms.Length);
                    ms.Close();
    
                    return Convert.ToBase64String(arr);
                }
                catch
                {
                    return null;
                }
            }
           
    
          
            
        }

    别忘了,项目中应该还会要一个ffmpeg.exe你还幺额外去下载。

    希望可以帮到你。

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • 已标记为答案 BillQu0002 2021年5月20日 6:42
    2021年5月19日 9:08
    版主