NAudio - seeking and navigation to play from the specified position
Asked Answered
I

4

8

I'm using NAudio library in a C# application. I'm trying to seek an audio (*.mp3 file) to the position I want. However I didn't figure out how to do it.

//Play the file starting from 16th second
waveStream.Seek(16, SeekOrigin.Begin);

And ... It played starting almost from the beginning, but not from the 16th second. I also found a solution I thought true:

waveStream.Seek(waveStream.WaveFormat.AverageBytesPerSecond * 16, SeekOrigin.Begin);

It seems it's closer the truth. Is my resolving true or not? If not what should I do?

Intolerance answered 29/4, 2012 at 11:27 Comment(0)
G
10

You can set Position directly on a WaveStream, which must be converted into a byte offset - so yes, multiplying the average bytes per second by the number of seconds will get you to the right place (at least with regular PCM WAV files). WaveStream also has a helper property called CurrentTime allowing you to use a TimeSpan and it does the same calculation for you.

audioFile.Position += audioFile.WaveFormat.AverageBytesPerSecond * 15;

Greiner answered 30/4, 2012 at 9:25 Comment(0)
V
9

If someone still has this problem and can not figure it out. Then here is an example:

myWaveStream.CurrentTime = myWaveStream.CurrentTime.Add(new TimeSpan(0, hours, minutes, seconds, milliseconds));

myWaveStream.CurrentTime = myWaveStream.CurrentTime.Subtract(new TimeSpan(0, hours, minutes, seconds, milliseconds));
Valuer answered 17/6, 2013 at 16:21 Comment(1)
That’s it. For some reason, the ISampleProvider’s extension method Skip() (that should take the same TimeSpan) doesn’t work, but this calculation approach does. Thanks!Assent
E
1

I created a navigation using a trackBar with 4 ticks per second (1 tick at 250ms):

trackBar1.Maximum = (int)stream.TotalTime.TotalSeconds * 4;

In a timer tick handler, called at each 250ms, an update of the trackbar is done as following:

double ms = stream.Position * 1000.0 / output.OutputWaveFormat.BitsPerSample / output.OutputWaveFormat.Channels * 8.0 / output.OutputWaveFormat.SampleRate;
trackBar1.Value = (int) (4 * ms / 1000);

In order to set the position (after scrolling), this formula worked:

double ms = trackBar1.Value * 1000.0 / 4.0;
stream.Position = (long)(ms * output.OutputWaveFormat.SampleRate * output.OutputWaveFormat.BitsPerSample * output.OutputWaveFormat.Channels / 8000.0) & ~1;
Elevation answered 4/7, 2020 at 20:19 Comment(0)
U
0

Winforms Trackbar Min=0 Max=100 (see Mark Heath answere the owner of the Naudio- Lib):

    private void TrkbrPosition_ValueChanged(object sender, EventArgs e)
    {
        if (audioFile != null)
        {
            var lengthInBytes = audioFile.Length;
            var pos = (lengthInBytes/100) * TrkbrPosition.Value;
            audioFile.Position = pos;
        }
    }
Unkindly answered 30/5, 2022 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.