我只是想听听我对使用NAudio的麦克风所说的话,这是我的代码到目前为止,但问题是我听不到任何声音。任何帮助将不胜感激。
public partial class frmMain : Form
{
private WaveIn waveIn; // Gets an audio from microphone
private WaveOut waveOut; // Sends audio to speaker
private BufferedWaveProvider waveProvider; // Gets an audio from stream
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
waveOut = new WaveOut();
waveIn = new WaveIn();
waveProvider = new BufferedWaveProvider(waveIn.WaveFormat);
waveOut.Init(waveProvider);
waveIn.DataAvailable += waveIn_DataAvailable;
waveOut.Play();
}
private void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
waveProvider.Read(e.Buffer, 0, e.BytesRecorded);
}
private void btnStop_Click(object sender, EventArgs e)
{
waveIn.StopRecording();
waveIn.Dispose();
}
private void btnStart_Click(object sender, EventArgs e)
{
waveIn.StartRecording();
}
}
我将在网络编程中使用这种情况,我将数据从麦克风发送到套接字,然后在客户端,BufferedWaveProvider将读取数据,然后将其发送到扬声器。如果有更好的方法,请另外发表评论。
TIA
答案 0 :(得分:8)
承诺的示例代码。代码用于包含两个按钮的表单(名为StartBtn和StopBtn)。
public partial class Form1 : Form
{
private WaveIn waveIn = null;
private BufferedWaveProvider waveProvider = null;
private WaveOut waveOut = null;
public Form1()
{
InitializeComponent();
}
private void StartBtn_Click(object sender, EventArgs e)
{
if (waveIn != null)
return;
// create wave input from mic
waveIn = new WaveIn(this.Handle);
waveIn.BufferMilliseconds = 25;
waveIn.RecordingStopped += waveIn_RecordingStopped;
waveIn.DataAvailable += waveIn_DataAvailable;
// create wave provider
waveProvider = new BufferedWaveProvider(waveIn.WaveFormat);
// create wave output to speakers
waveOut = new WaveOut();
waveOut.DesiredLatency = 100;
waveOut.Init(waveProvider);
waveOut.PlaybackStopped += wavePlayer_PlaybackStopped;
// start recording and playback
waveIn.StartRecording();
waveOut.Play();
}
void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
// add received data to waveProvider buffer
if (waveProvider != null)
waveProvider.AddSamples(e.Buffer, 0, e.BytesRecorded);
}
private void StopBtn_Click(object sender, EventArgs e)
{
if (waveIn != null)
waveIn.StopRecording();
}
void waveIn_RecordingStopped(object sender, StoppedEventArgs e)
{
// stop playback
if (waveOut != null)
waveOut.Stop();
// dispose of wave input
if (waveIn != null)
{
waveIn.Dispose();
waveIn = null;
}
// drop wave provider
waveProvider = null;
}
void wavePlayer_PlaybackStopped(object sender, StoppedEventArgs e)
{
// stop recording
if (waveIn != null)
waveIn.StopRecording();
// dispose of wave output
if (waveOut != null)
{
waveOut.Dispose();
waveOut = null;
}
}
}
请特别注意waveIn.BufferMilliseconds
和waveOut.DesiredLatency
设置,以减少延迟时间。
为了压缩网络传输数据,我建议使用不同的库来处理数据块。您可能需要调整BufferMilliseconds
值以减少开销并获得更好的压缩率。
Opus Codec看起来是一个合理的选择,C#为Opus.NET。