filoe / cscore

An advanced audio library, written in C#. Provides tons of features. From playing/recording audio to decoding/encoding audio streams/files to processing audio data in realtime (e.g. applying custom effects during playback, create visualizations,...). The possibilities are nearly unlimited.
Other
2.15k stars 451 forks source link

Get the recorded data when an event triggers #358

Closed mithunvs closed 5 years ago

mithunvs commented 5 years ago

I posted earlier about getting the data in the regular intervals in the same time of recording the audio and I got this code which works like a charm.This code gives the data at specified intervals (5 seconds in the sample code). Now I need the data to be available when an event triggers instead of regular intervals . Can you please suggest the modifications to be made on the existing code

`//1. init capture var soundIn = new WasapiLoopbackCapture(); soundIn.Initialize();

        //2. wrap capture to an audio stream
        var soundInSource = new SoundInSource(soundIn);

        //3. wrap audio stream within an NotificationSource in order to intercept samples
        var notificationSource = new NotificationSource(soundInSource.ToSampleSource());
        notificationSource.Interval = 5000; //5 seconds
        notificationSource.BlockRead += (s, e) =>
        {
            var filename = $"{DateTime.Now.Ticks}.wav";

            //send data provided by eventargs to api
            using (var writer = new WaveWriter(filename, notificationSource.WaveFormat))
            {
                Debug.Assert(e.Data.Length == e.Length);
                writer.WriteSamples(e.Data, 0, e.Length);
            }

            var length = TimeConverterFactory.Instance.GetTimeConverterForSource(notificationSource)
                .ToTimeSpan(notificationSource.WaveFormat, e.Length);
            Console.WriteLine($"Written {e.Length} ({length:g}) samples to file {filename}");
        };

        //4. convert whole chain back to WaveSource to write wave to the file
        var waveSource = notificationSource.ToWaveSource();

        //buffer for reading from the wavesource
        byte[] buffer = new byte[waveSource.WaveFormat.BytesPerSecond / 2];

        //5. if capture serves new data to the audio stream chain, read from the last chain element (wavesource) and write it back to the file
        // this will process audio data from capture to notificationSource to wavesource and will also trigger the blockread event of the notificationSource
        soundInSource.DataAvailable += (s, e) =>
        {
            int read;
            while ((read = waveSource.Read(buffer, 0, buffer.Length)) > 0)
            {
                //do nothing
            }
        };

        soundIn.Start();

        Console.ReadKey(); `
filoe commented 5 years ago

Duplicate