how to record and play audio multiple times, replacing audio file NAdio

439 views Asked by At

I have here my code form various NAudio tutorials. I have made a simple recorder. which has a record button, stop recording button then play button. for the first recording it works perfectly fine and i can even play my audio. but whenever i start recording again it displays an error where my filename is being used by another process. i dont know what process i should stop.

here is my code

    public void recorUser()
    {
        waveInStream = new WaveIn();
       // writer = null;
        writer = new WaveFileWriter(@"D:\2.wav", waveInStream.WaveFormat);
        waveInStream.DataAvailable += new EventHandler<WaveInEventArgs>(waveInStream_DataAvailable);
        waveInStream.StartRecording();
    }
    void waveInStream_DataAvailable(object sender, WaveInEventArgs e)
    {
        writer.Write(e.Buffer, 0, e.BytesRecorded);
    }
    public void stopRecordUser()
    {
        waveInStream.StopRecording();
        waveInStream.Dispose();
        waveInStream = null;
        writer.Close();
        writer = null;
    }
    public void playRecordedUser()
    {
        pcm = new WaveChannel32(new WaveFileReader(@"D:\2.wav"));
        //.PadWithZeroes = false;
        reductionStream = new BlockAlignReductionStream(pcm);
        waveOutDevice = new DirectSoundOut();
        waveOutDevice.PlaybackStopped += new EventHandler<StoppedEventArgs>(audioOutput_PlaybackStopped);
        waveOutDevice.Init(reductionStream);
        waveOutDevice.Play();
        // pcm.Close();
        // waveOutDevice.Dispose();
    }

thanks in advance for your ansers. :) please help me.

1

There are 1 answers

0
Mark Heath On
  1. Don't use BlockAlignReductionStream. Whatever tutorial you saw this in is horribly out of date.
  2. Use AudioFileReader instead of WaveFileReader and WaveChannel32.
  3. Dispose the audio file reader when you finish playing (e.g. in the PlaybackStopped handler)