naudio record sound from microphone then save

前端 未结 1 1971
星月不相逢
星月不相逢 2020-12-05 08:20

I\'m having some issues with naudio and saving sound recordings. The code I currently have works to the point where it saves the wav file, but when I open it up, Windows Med

相关标签:
1条回答
  • 2020-12-05 08:36

    Your recordButton_Click code isn't recording, it's piping data from a WaveIn to a WaveOut, which will play the data coming from your source (microphone) directly to the output (speakers). It doesn't retain that data for later use, it just pipes it from one to the other. If you want to subsequently save that data to disk, you need to buffer it yourself.

    The saveResponse_Click on the other hand is starting the direct recording of data from the microphone to a wave file on disk. If you click your Save Response button, wait for a bit, then click your Stop button, you should get a recorded wave file.

    If you want to record directly to disk, this is fine. If you want to record to memory, then optionally write to disk, then you need to save the data as it comes in. Perhaps use a memory stream to hold the data while recording, then write that to the WaveFileWriter when it comes time to save the file.


    Here's the code I used for testing direct recording to a wave file on disk:

    public WaveIn waveSource = null;
    public WaveFileWriter waveFile = null;
    
    private void StartBtn_Click(object sender, EventArgs e)
    {
        StartBtn.Enabled = false;
        StopBtn.Enabled = true;
    
        waveSource = new WaveIn();
        waveSource.WaveFormat = new WaveFormat(44100, 1);
    
        waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
        waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);
    
        waveFile = new WaveFileWriter(@"C:\Temp\Test0001.wav", waveSource.WaveFormat);
    
        waveSource.StartRecording();
    }
    
    private void StopBtn_Click(object sender, EventArgs e)
    {
        StopBtn.Enabled = false;
    
        waveSource.StopRecording();
    }
    
    void waveSource_DataAvailable(object sender, WaveInEventArgs e)
    {
        if (waveFile != null)
        {
            waveFile.Write(e.Buffer, 0, e.BytesRecorded);
            waveFile.Flush();
        }
    }
    
    void waveSource_RecordingStopped(object sender, StoppedEventArgs e)
    {
        if (waveSource != null)
        {
            waveSource.Dispose();
            waveSource = null;
        }
    
        if (waveFile != null)
        {
            waveFile.Dispose();
            waveFile = null;
        }
    
        StartBtn.Enabled = true;
    }
    
    0 讨论(0)
提交回复
热议问题