Skip to content

Instantly share code, notes, and snippets.

@SnowyPainter
Created March 20, 2020 16:01
Show Gist options
  • Save SnowyPainter/e26d7af597b1094995e2a6e28b663048 to your computer and use it in GitHub Desktop.
Save SnowyPainter/e26d7af597b1094995e2a6e28b663048 to your computer and use it in GitHub Desktop.
[C# NAudio] Record and return audio stream. get the float maximum value to show the progress
using NAudio.Utils;
using NAudio.Wave;
using System;
using System.IO;
namespace IDONTKNOW
{
public class AudioRecord
{
private void waveMaxSample(WaveInEventArgs e, Action<float> handler)
{
if (waveWriter != null) //Aliving waveWrter(filewriter), write all bytes in buffer
{
waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
waveWriter.Flush();
}
float maxRecorded = 0.0f;
for (int i = 0;i < e.BytesRecorded;i+=2) //loop for bytes
{
//convert to float
short sample = (short)((e.Buffer[i + 1] << 8) |
e.Buffer[i + 0]);
var sample32 = sample / 32768f;
if (sample32 < 0) sample32 = -sample32; // alter to absolute value
if (sample32 > maxRecorded) maxRecorded = sample32; //update maximum
}
handler(maxRecorded); //pass the handle
}
private void OnRecordingStopped(object sender, StoppedEventArgs e)
{
if (waveWriter != null)
{
waveWriter.Close();
waveWriter = null;
}
}
private WaveIn wave;
private WaveFileWriter waveWriter;//opening memoryStream and write in dataavailable event
private Stream memoryStream; //for save
public AudioRecord(int device, int sampleRate, int channels, Action<float> dataAvailableHandler)
{
int waveInDevices = WaveIn.DeviceCount;
if(waveInDevices < 1)
{
throw new Exception("there's no connectable devices in computer : AudioRecord constructor");
}
wave = new WaveIn();
wave.DeviceNumber = device;
wave.DataAvailable += (sender, e) =>
{
waveMaxSample(e, dataAvailableHandler);
};
wave.RecordingStopped += OnRecordingStopped;
wave.WaveFormat = new WaveFormat(sampleRate, channels);
}
public void Start()
{
memoryStream = new MemoryStream();
//WaveFileWriter with ignoredisposesream memorystream
waveWriter = new WaveFileWriter(new IgnoreDisposeStream(memoryStream), wave.WaveFormat);
wave.StartRecording();
}
public Stream Stop()
{
if (waveWriter == null || memoryStream == null) return null;
wave.StopRecording();
return memoryStream;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment