gpt4 book ai didi

c# - 从麦克风输入录制现场音频并同时保存

转载 作者:太空狗 更新时间:2023-10-29 22:30:40 26 4
gpt4 key购买 nike

我试图用 C# 开发一个录音机。我尝试了很多方法,比如NAudio、DirectX、Microsoft.Xna.Framework.Audio等。

一切都给出相同的结果。停止录音后,输出文件 mp3/wav 得到保存。

mp3/wav 文件是在开头创建的(没有内容 - 0 字节)

我正在尝试创建一个可以实时/同时保存音频的应用程序。

    private void StartRecording() {
this.WaveSource = new WaveInEvent { WaveFormat = new WaveFormat(44100, 1) };

this.WaveSource.DataAvailable += this.WaveSourceDataAvailable;
this.WaveSource.RecordingStopped += this.WaveSourceRecordingStopped;

this.WaveFile = new WaveFileWriter(@"C:\Sample.wav", this.WaveSource.WaveFormat);

this.WaveSource.StartRecording();
}

private void StopRecording() {
this.WaveSource.StopRecording();
}

void WaveSourceDataAvailable(object sender, WaveInEventArgs e) {
if (this.WaveFile != null) {
this.WaveFile.Write(e.Buffer, 0, e.BytesRecorded);
this.WaveFile.Flush();
}
}

void WaveSourceRecordingStopped(object sender, StoppedEventArgs e) {
if (this.WaveSource != null) {
this.WaveSource.Dispose();
this.WaveSource = null;
}

if (this.WaveFile != null) {
this.WaveFile.Dispose();
this.WaveFile = null;
}
}

最佳答案

我已经解决了 NAudio 库本身的问题。对现有代码进行少量修改。

public class Recorder {

WaveIn sourceStream;
WaveFileWriter waveWriter;
readonly String FilePath;
readonly String FileName;
readonly int InputDeviceIndex;

public Recorder(int inputDeviceIndex, String filePath, String fileName) {
InitializeComponent();
this.InputDeviceIndex = inputDeviceIndex;
this.FileName = fileName;
this.FilePath = filePath;
}

public void StartRecording(object sender, EventArgs e) {
sourceStream = new WaveIn {
DeviceNumber = this.InputDeviceIndex,
WaveFormat =
new WaveFormat(44100, WaveIn.GetCapabilities(this.InputDeviceIndex).Channels)
};

sourceStream.DataAvailable += this.SourceStreamDataAvailable;

if (!Directory.Exists(FilePath)) {
Directory.CreateDirectory(FilePath);
}

waveWriter = new WaveFileWriter(FilePath + FileName, sourceStream.WaveFormat);
sourceStream.StartRecording();
}

public void SourceStreamDataAvailable(object sender, WaveInEventArgs e) {
if (waveWriter == null) return;
waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
waveWriter.Flush();
}

private void RecordEnd(object sender, EventArgs e) {
if (sourceStream != null) {
sourceStream.StopRecording();
sourceStream.Dispose();
sourceStream = null;
}
if (this.waveWriter == null) {
return;
}
this.waveWriter.Dispose();
this.waveWriter = null;
recordEndButton.Enabled = false;
Application.Exit();
Environment.Exit(0);
}
}

关于c# - 从麦克风输入录制现场音频并同时保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30099459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com