情境:
我正在使用NAudio 1.5,我试图以I,格式PCM,8位,22050hz的IWaveProvider录制Sinus波,如下所示:
Private Sub record(ByVal waveForm As String, _
ByVal duration As Integer, _
ByVal frequency As Integer, _
ByVal amplitude As Integer, _
ByVal sampleRate As Integer)
Dim wave As IWaveProvider = _
Audio.SoundModulWaveFormProviderFactory.createWaveForm(waveForm, _
frequency, amplitude, sampleRate)
Dim memStream As New System.IO.MemoryStream()
Dim writer As New WaveFileWriter(memStream, wave.WaveFormat)
Dim numberOfBytes As Integer = writer.WaveFormat.AverageBytesPerSecond
Dim buffer(numberOfBytes) As Byte
Dim i As Integer
Dim count As Integer
For i = 1 To duration
count = wave.Read(buffer, 0, numberOfBytes)
writer.Write(buffer, 0, count)
Next
writer.Flush()
Try
Me.audioStream = New MemoryStream()
memStream.WriteTo(Me.audioStream)
Catch ex As Exception
Trace.WriteLine(ex.Message)
End Try
writer.Close()
recorded = True
End Sub
然后将内存流移交给正在解析整个wave文件的函数,并将其包含在声音列表中。
问题
上面提到的函数期望波数据的长度从字节位置42到45.不幸的是,它似乎总是为0.因此我不会有任何长度。
问题:
如何确保WaveFileWriter将此信息写入MemoryStream?或者它只在写入文件时才这样做?
也许有不同的方法达到同一目标?
更新
WaveFileWriter在直接写入文件时确实包含波形数据长度。
答案 0 :(得分:1)
只有在您调用Close时,WaveFileWriter才会设置长度。所以移动writer.Close在你的Try块之前。此外,NAudio有一个名为IgnoreDisposeStream的辅助类,您可以使用它来防止MemoryStream在您需要之前被丢弃。
Dim writer As New WaveFileWriter(new IgnoreDisposeStream(memStream) ...
...
writer.Close()
Try
Me.audioStream = New MemoryStream()
memStream.WriteTo(Me.audioStream)
Catch ex As Exception
Trace.WriteLine(ex.Message)
End Try
recorded = True