I try to record some audio(after Record click button) into a MemoryStream and then Play it in visual studio(WPF) using NAudio. I generated a RawSourceWaveStream that gets the myMemoryStream when click play button but I think this is bugging the code.
It doesn't play... here is my code.
Where am I go wrong?
namespace RecAndPlay
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private WaveIn myWaveIn=null;
private MemoryStream myMemoryStream = null;
private WaveOut myWaveOut= null;
private RawSourceWaveStream myRaw = null;
private void myRecord(object sender, RoutedEventArgs e)
{
{
RecordButton.Content = "Stop Rec";
myWaveIn = new WaveIn();
myWaveIn.WaveFormat = new WaveFormat(44100, 1);
myWaveIn.DeviceNumber = 0;
myWaveIn.DataAvailable += myWaveIn_DataAvailable;
myMemoryStream = new MemoryStream();
myWaveIn.StartRecording();
}
}
void myWaveIn_DataAvailable(object sender, WaveInEventArgs e)
{
myMemoryStream.Write(e.Buffer, 0, e.BytesRecorded);
}
private void myPlay(object sender, RoutedEventArgs e)
{
myWaveOut = new WaveOut();
myRaw = new RawSourceWaveStream(myMemoryStream, myWaveIn.WaveFormat);
myWaveOut.Init(myRaw);
myWaveOut.Play();
}
private void mtStopRec(object sender, RoutedEventArgs e)
{
myWaveIn.StopRecording();
RecordButton.Content = "Record";
}
}
}
You need to set the Position
on your MemoryStream
to 0 before playing the audio. Also, bear in mind that with this solution you should not attempt to play while you are still recording.