Ali Tor Ali Tor - 9 months ago 207
C# Question

How to get current time while streaming mp3 using NAudio?

I have a code to stream mp3 from url. I want to show the current time of the mp3 player in UI. I tried it using

, but it couldn't work for me.
How can I do that?

My code:

// to get url stream,to create BufferedWaveProvider

int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
provider.AddSamples(buffer, 0, decompressed);
if (provider.BufferedDuration.Seconds > 2 && waveOut == null)
waveOut = new WaveOut();
if (waveOut != null)
currentTime = (int)(waveOut.GetPosition() * 1d / AvgBytesPerSec);
while (bytesRead > 0 || waveOut.PlaybackState == PlaybackState.Playing);


I think the only change you need to make to your code is to use waveOut.OutputWaveFormat.AverageBytesPerSecond instead of the AvgBytesPerSec property you are currently using. The IWavePosition interface (which is what you are actually using here) "thinks" in hardware terms, so if you are using a format that has to be converted before the hardware can use it, the hardware byte rate will be different than your source byte rate.

Note that the position returned by GetPosition() is only since playback was last started. If waveOut.Stop() is called, the position is reset to 0 when playback is started again. Mapping the position to the source is up to the caller (which is really simple; just track where you last started playback on the source and add it to the position returned. Buffering makes it more complicated, but still completely doable).

I wrote the original IWavePosition interface & implementations for NAudio. It works great in the project I built it for. :)