Naudio 录制麦克风 X 秒
Posted
技术标签:
【中文标题】Naudio 录制麦克风 X 秒【英文标题】:Naudio record microphone for X amount of seconds 【发布时间】:2013-12-11 21:55:25 【问题描述】:目前我可以使用 Naudio .dll 记录麦克风输入:
public void recordInput()
Console.WriteLine("Now recording...");
waveSource = new WaveIn();
waveSource.WaveFormat = new WaveFormat(16000, 1);
waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);
//string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".wav");
string tempFile = Path.Combine(@"C:\Users\Nick\Desktop", "test.wav");
waveFile = new WaveFileWriter(tempFile, waveSource.WaveFormat);
waveSource.StartRecording();
myTimer.Interval = 5000;
myTimer.Tick += new EventHandler(myTimer_Tick);
myTimer.Start();
目前我使用事件处理程序等待 5 秒,然后 onTick 我停止录制。但是,这会导致问题,因为我无法在我调用的代码的主要部分中等待录制任务完成:
public string voiceToText()
recordInput();
//Somehow wait here until record is done then proceed.
convertToFlac();
return "done";
我尝试将 Naudio 放入线程并使用 waitOne();
,但 waveSource.StartRecording();
已放入事件处理程序并线程预期。我也尝试过使用Thread.Sleep(5000)
并在该线程完成后停止录制,但由于某种原因,音频只记录了前 500 毫秒的音频。
我对 c# 很陌生,并不完全了解线程,因此欢迎任何帮助或单独的方法。
【问题讨论】:
【参考方案1】:我知道这是一个老话题,但这是我为我的一个项目编写的一些代码,它记录了 x 秒的音频(它使用 NAudio.Lame 将波形文件转换为 mp3):
public class Recorder
/// <summary>
/// Timer used to start/stop recording
/// </summary>
private Timer _timer;
private WaveInEvent _waveSource;
private WaveFileWriter _waveWriter;
private string _filename;
private string _tempFilename;
public event EventHandler RecordingFinished;
/// <summary>
/// Record from the mic
/// </summary>
/// <param name="seconds">Duration in seconds</param>
/// <param name="filename">Output file name</param>
public void RecordAudio(int seconds, string filename)
/*if the filename is empty, throw an exception*/
if (string.IsNullOrEmpty(filename))
throw new ArgumentNullException("The file name cannot be empty.");
/*if the recording duration is not > 0, throw an exception*/
if (seconds <= 0)
throw new ArgumentNullException("The recording duration must be a positive integer.");
_filename = filename;
_tempFilename = $"Path.GetFileNameWithoutExtension(filename).wav";
_waveSource = new WaveInEvent
WaveFormat = new WaveFormat(44100, 1)
;
_waveSource.DataAvailable += DataAvailable;
_waveSource.RecordingStopped += RecordingStopped;
_waveWriter = new WaveFileWriter(_tempFilename, _waveSource.WaveFormat);
/*Start the timer that will mark the recording end*/
/*We multiply by 1000 because the Timer object works with milliseconds*/
_timer = new Timer(seconds * 1000);
/*if the timer elapses don't reset it, stop it instead*/
_timer.AutoReset = false;
/*Callback that will be executed once the recording duration has elapsed*/
_timer.Elapsed += StopRecording;
/*Start recording the audio*/
_waveSource.StartRecording();
/*Start the timer*/
_timer.Start();
/// <summary>
/// Callback that will be executed once the recording duration has elapsed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StopRecording(object sender, ElapsedEventArgs e)
/*Stop the timer*/
_timer?.Stop();
/*Destroy/Dispose of the timer to free memory*/
_timer?.Dispose();
/*Stop the audio recording*/
_waveSource.StopRecording();
/// <summary>
/// Callback executed when the recording is stopped
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RecordingStopped(object sender, StoppedEventArgs e)
_waveSource.DataAvailable -= DataAvailable;
_waveSource.RecordingStopped -= RecordingStopped;
_waveSource?.Dispose();
_waveWriter?.Dispose();
/*Convert the recorded file to MP3*/
ConvertWaveToMp3(_tempFilename, _filename);
/*Send notification that the recording is complete*/
RecordingFinished?.Invoke(this, null);
/// <summary>
/// Callback executed when new data is available
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataAvailable(object sender, WaveInEventArgs e)
if (_waveWriter != null)
_waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
_waveWriter.Flush();
/// <summary>
/// Converts the recorded WAV file to MP3
/// </summary>
private void ConvertWaveToMp3(string source, string destination)
using (var waveStream = new WaveFileReader(source))
using(var fileWriter = new LameMP3FileWriter(destination, waveStream.WaveFormat, 128))
waveStream.CopyTo(fileWriter);
waveStream.Flush();
/*Delete the temporary WAV file*/
File.Delete(source);
下面是如何在您的代码中使用它:
var rec = new Recorder();
/*This line allows us to be notified when the recording is complete and the callback 'OnRecordingFinished' will be executed*/
rec.RecordingFinished += OnRecordingFinished;
rec.RecordAudio(seconds, recPath);
private void OnRecordingFinished(object sender, RecordingContentArgs e)
//Put your code here to process the audio file
【讨论】:
【参考方案2】:如果您没有在 Windows 窗体或 WPF 应用程序中运行,那么您应该改用WaveInEvent
,以便设置后台线程来处理回调。 WaveIn
的默认构造函数使用 Windows 消息。
【讨论】:
很高兴知道这一点。我现在可以毫无例外地将它放在一个线程中。对仅记录 5 秒间隔的最佳方式有何建议? 您可以通过跟踪在 DataAvailable 事件中收到的字节数(并使用 WaveFormat.AverageBytesPerSecond)来了解您记录了多少以上是关于Naudio 录制麦克风 X 秒的主要内容,如果未能解决你的问题,请参考以下文章