如何在使用 NAudio 流式传输 mp3 时获取当前时间?

How to get current time while streaming mp3 using NAudio?

我有一个代码可以从 url 流式传输 mp3。我想在 UI 中显示 mp3 播放器的当前时间。我尝试使用 WaveOut.GetPosition,但它对我不起作用。 我该怎么做?

我的代码:

do
 {
    //..codes 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();
       waveOut.Init(provider);
       waveOut.Play();
    }
    if (waveOut != null)
    {
       currentTime = (int)(waveOut.GetPosition() * 1d / AvgBytesPerSec);
    }
 }
 while (bytesRead > 0 || waveOut.PlaybackState == PlaybackState.Playing);

你试过属性当前时间和属性位置吗?

mp3Reader = new Mp3FileReader("example.mp3");

waveOut.Init(mp3Reader);

waveOut.Play();

// reposition to five seconds in
mp3Reader.CurrentTime = TimeSpan.FromSeconds(5.0);

所以 mp3Reader.CurrentTime 我认为应该给你你需要的东西

希望对您有所帮助

我认为您需要对代码进行的唯一更改是使用 waveOut.OutputWaveFormat.AverageBytesPerSecond 而不是您当前使用的 AvgBytesPerSec 属性。 IWavePosition 接口(这是你在这里实际使用的)"thinks" 在硬件方面,所以如果你使用的格式在硬件可以使用之前必须转换,硬件字节率将与您的源字节率不同。

请注意,GetPosition() 返回的位置只是自上次开始播放以来的位置。如果调用 waveOut.Stop(),则当再次开始播放时,该位置将重置为 0。将位置映射到源由调用者决定(这非常简单;只需跟踪您上次在源上开始播放的位置并将其添加到返回的位置。缓冲使它变得更复杂,但仍然完全可行)。

我为 NAudio 编写了原始的 IWavePosition 接口和实现。它在我为其构建的项目中运行良好。 :)