0

I have a problem with MediaFoundationEncoder

I need to record from input device file in AAC format, I write the following code:

    private Timer timer;
    private static IWaveIn _waveIn;
    private static IWaveProvider _provider;
    public void StartRecorder()
    {
        _waveIn = new WaveInEvent
            {
                WaveFormat = new WaveFormat(8000, 1)

            };
        _provider = new WaveInProvider(_waveIn);

        _waveIn.DataAvailable += OnDataAvailable;
        _waveIn.StartRecording();

        //for testing purpose write only first 5 seconds.
        timer = new Timer(5000);
        timer.Elapsed += (sender, args) => Stop();
        timer.Start();


    }

    private void Stop()
    {
        timer.Stop();
        _waveIn.StopRecording();
        _waveIn.Dispose();
        _waveIn = null;
        var outputFilename = String.Format("D:\\{0:yyy-mm-dd HH-mm-ss}.aac", DateTime.Now);
        MediaFoundationEncoder.EncodeToAac(_provider, outputFilename);
        _provider = null;
    }

Also I tried to use MediaFoundationEncoder.EncodeToWma - BUT the file size continued to grow even after stopping the recording and disposed _waveIn. Timeline in file is corrrect, something writes to file trash bytes.

P.S. Im using the lastet build of NAudio (1.7).

Roman Badiornyi
  • 1,509
  • 14
  • 28
  • 1
    A couple of things to try: 1. run the WPF demo app to enumerate your MF encoders and decoders and check you really do have an AAC encoder. 2. try with a ".mp4" file extension instead. – Mark Heath Jun 01 '13 at 18:02
  • Thanks Mark for helping, you are right, the problem was with MF encoders, I run the code above in windows 8 succesfully. But the problem with file size growing still exists. Can you help also with this issue? – Roman Badiornyi Jun 02 '13 at 16:42

1 Answers1

0

The file size growing indefinitely issue is likely because your input provider never returns 0 from its Read method. I'd recommend you write all your audio to a memory stream and then use that with a RawSourceWaveProvider to form the input to your encoder. (remember to set the MemoryStream position to 0 before encoding)

Mark Heath
  • 48,273
  • 29
  • 137
  • 194