使用naudio

时间:2017-03-16 11:54:29

标签: uwp windows-10 naudio speech

我正在尝试使用naudio在uwp中记录用户语音。以下是初始化naudio以捕获和写入磁盘的代码:

sourcestream = new WasapiCaptureRT();
sourcestream.WaveFormat = new WaveFormat(8000, 8, 1);

sourcestream.DataAvailable += OnDataAvailable;
sourcestream.RecordingStopped += OnRecordingStopped;

sourcestream.StartRecording();

file = await KnownFolders.MusicLibrary.CreateFileAsync("audio.wav", CreationCollisionOption.ReplaceExisting);
MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto);

memorystream = await file.OpenStreamForWriteAsync();

writer = new WaveFileWriterRT(memorystream, sourcestream.WaveFormat);

sourcestream.StartRecording();

但执行时

memorystream = await file.OpenStreamForWriteAsync();

抛出异常并执行以下代码:

 DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
        UnhandledException += (sender, e) =>
        {
            if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
        };

    }

代码中的例外是

  

不支持的波形格式

我尝试在控制台应用程序中执行相同操作,一切正常。但是当我尝试在UWP中执行此操作时,会显示上述错误。

此错误的原因是什么?

1 个答案:

答案 0 :(得分:0)

错误"不支持的波形格式"由WasapiCaptureRT.cs包中的文件NAudio的以下代码段引发。

if (!audioClient.IsFormatSupported(AudioClientShareMode.Shared, waveFormat))
{
    throw new ArgumentException("Unsupported Wave Format");
}

因此,似乎不支持您通过代码行sourcestream.WaveFormat = new WaveFormat(8000, 8, 1);提供的wave格式。像44kHz这样的波形可以正常工作。

sourcestream.WaveFormat = new WaveFormat(44100, 16, 1);

更新

  

文件已保存但未记录任何内容。

由于您未提供OnDataAvailable方法的代码,请尝试以下操作:

 private async void btnrecord_Click(object sender, RoutedEventArgs e)
 {
     sourcestream = new WasapiCaptureRT();
     sourcestream.RecordingStopped += OnRecordingStopped;
     sourcestream.DataAvailable += OnDataAvailable;
     file = await KnownFolders.MusicLibrary.CreateFileAsync("audio2.wav", CreationCollisionOption.GenerateUniqueName);
     var radomsteam = await file.OpenAsync(FileAccessMode.ReadWrite);
     streamwriter = radomsteam.AsStreamForWrite(); ();
     sourcestream.StartRecording();
 }
 private void OnDataAvailable(object sender, WaveInEventArgs e)
 { 
     writer = new WaveFileWriterRT(streamwriter, sourcestream.WaveFormat);
     writer.Write(e.Buffer, 0, e.BytesRecorded);
     writer.Flush();     
 }