Naudio录制和播放音频

时间:2014-12-17 18:48:14

标签: vb.net audio-recording naudio

我放弃了WaveIn p / invoke后我正在使用NAudio 1.7 ...无论如何,我正在制作一个VoIP应用程序,我发现的示例代码使用WaveFileWriter输出到磁盘,我不希望这样,所以我使用了memoryStream重载。

问题是当我在使用SoundPlayer类停止录制后尝试播放流时,它只是不播放并继续代码,但如果我如下所示保存它,我可以在VLC中播放,但是,如果我尝试从文件本身加载它,它也不会播放,这次抛出“Wav标题已损坏”或其他东西,如果我没有将它设置为位置0,则抛出流。

当我保存时,Windows是否设置了wav文件头?为什么VLC可以播放它而SoundPlayer甚至不能保存它?

   Private waveFile As WaveFileWriter
Private newWave As New NAudio.Wave.WaveIn

Private memstream As New MemoryStream

Public Sub StartRecording()
    newWave.WaveFormat = New WaveFormat(44100, 1)

    waveFile = New WaveFileWriter(memstream, newWave.WaveFormat)

    AddHandler newWave.DataAvailable, AddressOf RecordedDataAvailable
    AddHandler newWave.RecordingStopped, AddressOf RecordingStopped

    newWave.StartRecording()
End Sub

Private Sub RecordedDataAvailable(sender As Object, e As NAudio.Wave.WaveInEventArgs)
    If waveFile IsNot Nothing Then
        waveFile.Write(e.Buffer, 0, e.BytesRecorded)
        waveFile.Flush()
    End If
End Sub

Private Sub RecordingStopped(sender As Object, e As NAudio.Wave.StoppedEventArgs)
    Dim fileName As String = Application.StartupPath & "\Test"

    File.WriteAllBytes(fileName & ".wav", memstream.GetBuffer)

    memstream.Position = 0

    Dim player As New SoundPlayer(memstream)
    player.Play()
End Sub

1 个答案:

答案 0 :(得分:1)

我知道这是C#,但我认为你明白了;) 我试着和你一样做,这对我有用。

private WaveFileWriter writer;
private WaveIn waveIn;
private MemoryStream memoryStream;

public MainWindow()
{
  InitializeComponent();

  waveIn = new WaveIn();

  waveIn.DataAvailable += OnWaveInDataAvailable;
  waveIn.RecordingStopped += OnWaveInRecordingStopped;
}

private void OnWaveInDataAvailable(object sender, WaveInEventArgs waveInEventArgs)
{
  writer.Write(waveInEventArgs.Buffer, 0, waveInEventArgs.BytesRecorded);
  writer.Flush();
}

private void OnWaveInRecordingStopped(object sender, StoppedEventArgs stoppedEventArgs)
{
  Save();
}

private void Start()
{
  memoryStream = new MemoryStream();
  writer = new WaveFileWriter(new IgnoreDisposeStream(memoryStream), waveIn.WaveFormat);
  waveIn.StartRecording();
}

private void Stop()
{
  waveIn.StopRecording();
}

private void Save()
{
  using (var fileStream = File.Create("test.wav"))
  {
    memoryStream.Seek(0, SeekOrigin.Begin);
    memoryStream.CopyTo(fileStream);
  }
}

private void Play()
{
  var soundPlayer = new SoundPlayer(memoryStream);
  memoryStream.Seek(0, SeekOrigin.Begin);
  soundPlayer.Play();
}

private void OnRecordClick(object sender, RoutedEventArgs e)
{
  Start();
}

private void OnStopClick(object sender, RoutedEventArgs e)
{
  Stop();
}

private void OnPlayClick(object sender, RoutedEventArgs e)
{
  Play();
}

}