This project has moved. For the latest updates, please go here.

SystemArgumentException when trying to play MP3 file

Mar 3, 2011 at 2:03 PM

I get this exception when I trying to play an MP3 file. Any hints what this is caused?

 

System.ArgumentException: Value does not fall within the expected range.   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)   at NAudio.CoreAudioApi.AudioClient.Initialize(AudioClientShareMode shareMode, AudioClientStreamFlags streamFlags, Int64 bufferDuration, Int64 periodicity, WaveFormat waveFormat, Guid audioSessionGuid)   at NAudio.Wave.WasapiOut.Init(IWaveProvider waveStream)   at Prototype_Concept_2.views.AudioControl.play_PreviewContactDown(Object sender, ContactEventArgs e) in C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Concept_2\Prototype_Concept_2\views\AudioControl.xaml.cs:line 208   at Microsoft.Surface.Presentation.ContactEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)   at System.Windows.Input.InputManager.ProcessStagingArea()   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)   at Microsoft.Surface.Presentation.InputSurfaceProviderBase.DoProcessInput(Object obj)   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)   at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)   at System.Windows.Threading.DispatcherOperation.InvokeImpl()   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)   at System.Threading.ExecutionContext.runTryCode(Object userData)   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)   at System.Windows.Threading.DispatcherOperation.Invoke()   at System.Windows.Threading.Dispatcher.ProcessQueue()   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)   at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)   at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)   at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)   at System.Windows.Threading.Dispatcher.Run()   at System.Windows.Application.RunDispatcher(Object ignore)   at System.Windows.Application.RunInternal(Window window)   at System.Windows.Application.Run(Window window)   at System.Windows.Application.Run()   at Prototype_Concept_2.App.Main() in C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Concept_2\Prototype_Concept_2\obj\Debug\App.g.cs:line 0System.UnhandledExceptionEventArgs

Coordinator
Mar 3, 2011 at 2:11 PM

looks like some kind of error initializing WASAPI out. Debug into it and check the parameters that are being passed in.

Mark

Mar 3, 2011 at 2:24 PM

Thanks. I'm doing it that way:

 

waveOutDevice = new WasapiOut(AudioClientShareMode.Shared, 100);

logging.Logging.Logger.write("Try to play audiofile: " + (sender as Image).Tag as String);

mainOutputStream = CreateInputStream( (sender as Image).Tag as String);

waveOutDevice.Init(mainOutputStream);

waveOutDevice.Play();

 

And using the logger I verified that a valid filename is used.

Mar 3, 2011 at 3:02 PM

I also tried to 100% valid wave files, but the same error.

Coordinator
Mar 3, 2011 at 3:04 PM

its nothing to do with the file. You can't open Wasapi out. It may be to do with sample rate. What is the sample rate of the file you are playing?

Have a look at the NAudio Demo project for an example of how to correctly query Wasapi to provide a stream at the correct format.

Mark

Mar 3, 2011 at 3:19 PM

Do you mean the bitrate? It is 1141 kbps.

Coordinator
Mar 3, 2011 at 3:22 PM

do mainOutputStream.WaveFormat.ToString() and tell me what you see

Mar 3, 2011 at 3:33 PM

IeeeFloat

Coordinator
Mar 3, 2011 at 3:34 PM

Can you try to play your file using the NAudioDemo project using Wasapi out and see if that works?

Mark

Mar 3, 2011 at 3:42 PM

Ok I'll try it with this code:

 

private WaveStream CreateInputStream(string fileName)
        {
            WaveChannel32 inputStream;
            if (fileName.EndsWith(".wav"))
            {
                WaveStream readerStream = new WaveFileReader(fileName);
                if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
                {
                    readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
                    readerStream = new BlockAlignReductionStream(readerStream);
                }
                if (readerStream.WaveFormat.BitsPerSample != 16)
                {
                    var format = new WaveFormat(readerStream.WaveFormat.SampleRate,
                        16, readerStream.WaveFormat.Channels);
                    readerStream = new WaveFormatConversionStream(format, readerStream);
                }
                inputStream = new WaveChannel32(readerStream);
            }
            else if (fileName.EndsWith(".mp3"))
            {                
                WaveStream mp3Reader = new Mp3FileReader(fileName);
                WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(mp3Reader);
                WaveStream blockAlignedStream = new BlockAlignReductionStream(pcmStream);
                inputStream = new WaveChannel32(blockAlignedStream);
            }
            else
            {
                throw new InvalidOperationException("Unsupported extension");
            }
            // we are not going into a mixer so we don't need to zero pad
            //((WaveChannel32)inputStream).PadWithZeroes = false;
            volumeStream = inputStream;
            var meteringStream = new MeteringStream(inputStream, inputStream.WaveFormat.SampleRate / 10);
            meteringStream.StreamVolume += new EventHandler<StreamVolumeEventArgs>(meteringStream_StreamVolume);
            
            return meteringStream;
        }

Mar 3, 2011 at 3:50 PM

The same error. I noticed that on one machine it is running and on another it is not.

Coordinator
Mar 8, 2011 at 12:09 PM

what are the values of mainOutputStream.WaveFormat.SampleRate and mainOutputStream.WaveFormat.Channels?

can you run NAudioDemo in debug using Visual Studio and break on all errors to see the HResult that is being returned from AudioClient.Initialise?

 

Mark

Apr 8, 2011 at 3:52 PM
Edited Apr 8, 2011 at 4:14 PM

I have similar problem with ieee float. im getting Exception:

"MmException was unhandled by user code: No Driver calling acmFormatSuggest"

   at NAudio.MmException.Try(MmResult result, String function) in \NAudio\Wave\MmeInterop\MmException.cs:line 39
   at NAudio.Wave.Compression.AcmStream.SuggestPcmFormat(WaveFormat compressedFormat) in \NAudio\Wave\Compression\AcmStream.cs:line 103
   at NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(WaveStream sourceStream) \NAudio\WaveStreams\WaveFormatConversionStream.cs:line 29

Here's the wav file (Ieee float, 2channels, 32bits): http://tsmaestro.aspone.cz/aa.wav

To simulate the exception you can play the file by  NAudio Demo project (WasapiOut).

I made the file from tada.wav in C:/windows/media/ by using following code:

 public void Crop(string newFileNameTimeSpan startTimeSpan end)
    {
      TimeSpan originalPosition = Position;
      Stop();
 
 
      Position = start;
      
      using (WaveFileWriter writer = new WaveFileWriter(newFileNamemainOutputStream.WaveFormat))
      {
        byte[] buffer = new byte[mainOutputStream.WaveFormat.AverageBytesPerSecond];
 
        while (true)
        {
          double seconds = (end - Position).TotalSeconds;
 
          int read;
          if (seconds > 1read = buffer.Length;
          else if (seconds > 0)
          {
            //ak sa blizime ku koncu, nezoberieme cely buffer, ale iba jeho cast
            read = (int)(mainOutputStream.WaveFormat.AverageBytesPerSecond * seconds);
            read -= read % (mainOutputStream.WaveFormat.BitsPerSample / 8 * mainOutputStream.WaveFormat.Channels);
          }
          else break;
 
          int bytesRead = mainOutputStream.Read(buffer0read);
          if (bytesRead == 0)
            break;
          writer.WriteData(buffer0bytesRead);
        }
      }
 
      Position = originalPosition;
    }

 mainoutputstream is created by your CreateInputStreamMethod

Coordinator
Apr 14, 2011 at 9:13 PM

this file should now play with the latest NAudio demo code