0

Scenario:

I am using NAudio 1.5 and I am trying to record a Sinus wave from an IWaveProvider in format PCM, 8bit, 22050hz like this:

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

The memory stream is then handed over to a function that is parsing the whole wave file and includes it into a list of sounds.

Issue

The above mentioned function expects the lenght of the wave data to be from byte-position 42 to 45. Unfortunately it seems that this is always 0. Thus I dont get any length back.

Question:

How can I make sure that the WaveFileWriter is writing this information into the MemoryStream? Or does it only do that upon writing to a file?

Maybe there is a different way of reaching the same goal?

Update:

WaveFileWriter does include the wave data lenght when writing to a file directly.

Dynamicbyte
  • 541
  • 1
  • 5
  • 13

1 Answers1

1

the length is only set by the WaveFileWriter when you call Close. So move writer.Close up before your Try block. Also, NAudio has a helper class called IgnoreDisposeStream, which you can use to prevent your MemoryStream from getting disposed before you want it to.

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
Mark Heath
  • 48,273
  • 29
  • 137
  • 194