C# 录音录像合成代码
时间: 2023-07-12 07:34:27 浏览: 234
c#录音代码
以下是一个简单的 C# 录音录像合成的代码示例:
```csharp
using System;
using System.IO;
using System.Windows.Forms;
using Accord.Video.FFMPEG;
using NAudio.Wave;
namespace RecordAndMerge
{
public partial class MainForm : Form
{
private WaveInEvent waveIn;
private VideoFileWriter writer;
private string audioPath;
private string videoPath;
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
waveIn = new WaveInEvent();
waveIn.WaveFormat = new WaveFormat(44100, 1);
waveIn.DataAvailable += OnDataAvailable;
writer = new VideoFileWriter();
writer.Open("output.avi", Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, 30, VideoCodec.MPEG4);
audioPath = "output.wav";
videoPath = "output.avi";
}
private void OnDataAvailable(object sender, WaveInEventArgs e)
{
writer.WriteVideoFrame(GetScreenshot(), DateTime.Now - startTime);
File.WriteAllBytes(audioPath, e.Buffer);
}
private Bitmap GetScreenshot()
{
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
}
return bitmap;
}
private void btnStart_Click(object sender, EventArgs e)
{
waveIn.StartRecording();
startTime = DateTime.Now;
}
private void btnStop_Click(object sender, EventArgs e)
{
waveIn.StopRecording();
writer.Close();
// 合成音视频
using (var v = new VideoFileReader())
using (var a = new AudioFileReader(audioPath))
using (var combine = new MediaFoundationReader(videoPath))
using (var output = new MediaFoundationEncoder(combine.WaveFormat, "output.mp4"))
{
output.VideoBitrate = v.BitRate;
output.VideoFramerate = v.FrameRate;
output.AudioBitrate = a.WaveFormat.AverageBytesPerSecond * 8;
output.AudioChannels = a.WaveFormat.Channels;
output.AudioSampleRate = a.WaveFormat.SampleRate;
output.Initialize();
combine.CopyTo(output);
a.CopyTo(output);
output.Flush();
}
// 删除临时文件
File.Delete(audioPath);
File.Delete(videoPath);
MessageBox.Show("合成成功!");
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
waveIn.Dispose();
writer.Dispose();
}
}
}
```
需要使用 NuGet 安装 Accord.Video.FFMPEG 和 NAudio 库。在窗体中添加两个 Button 控件,分别用于开始录制和停止录制。在 MainForm_Load 方法中初始化音频录制和视频写入。在 OnDataAvailable 方法中将录制的音频写入到临时文件中,并将当前屏幕截图写入到视频帧中。在 btnStart_Click 方法中开始录制,并记录开始时间。在 btnStop_Click 方法中停止录制,关闭视频写入器,并使用 Accord 和 NAudio 库合成音视频。最后,删除临时文件,并弹出提示框。你可以根据实际需求进行调整和优化。
阅读全文