简体   繁体   中英

Continuous record and play audio in C# visual studio

I have been trying to record and play the audio simultaneously with out using a temporary wav file. And later I would like to create a VOIP chat program.

I have used the Naudio library to capture and play audio in C# and it seems to work quite well. below is the c # code that i have written:

using System.IO.Ports;
using NAudio.Wave;
using System.IO;

namespace VOIP
{
    public partial class Form1 : Form
    {
        WaveIn wab = new WaveIn();    
        MemoryStream s;        
        int k;


        public Form1()
        {
            InitializeComponent();
            wab.BufferMilliseconds = 100;
            wab.NumberOfBuffers=5;
            wab.DataAvailable += new EventHandler<WaveInEventArgs>(wa_DataAvailable);           
        }

        void wa_DataAvailable(object sender, WaveInEventArgs e)
        {                 

            Play(e.Buffer);         

        }

        private void Play(byte[] p)
        {
            WaveOut ou = new WaveOut();
            s = new MemoryStream(p);
            RawSourceWaveStream r = new RawSourceWaveStream(s, wab.WaveFormat);
            ou.Init(r);
            ou.Play();
            ou.Stop();
            ou.Dispose();
            s.Dispose();
            r.Dispose();

        }

        private void Form1_Load(object sender, EventArgs e)
        {


        }

        private void button1_Click(object sender, EventArgs e)
        {
           if (button1.Text == "Stop")
            {
                wab.StopRecording();
                button1.Text = "Record";
            }
           else if (button1.Text == "Record")
            {
                wab.StartRecording();
                button1.Text = "Stop";
            }            
        }


    }
}

The Problem is at the "Play" method .Since the waveout object is created and disposed every time the data is available : i can hear some clicking sound. Is there a way to avoid this way of creating and disposing object and instead just create one object and then initialize with the new data. I also observed that the memory consumed by this program keeps increasing.

Thanks in advance. sanatan

Use a BufferedWaveProvider, and as audio arrives, decompress it and add it to the BufferedWaveProvider. Then have a single instance of WaveOut that is playing constantly from the BufferedWaveProvider.

The source code for NAudioDemo shows how to do this in the chat example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM