SDL_Mixer: Getting current track position

im just getting started using SDL_Mixer by creating a music player(a very simple one at that), and one of the struggles ive run into is getting the current position of the current track playing. I want it for a few reasons, like to be able to skip forward or backward by x(probably 10) amount of seconds, or to be able to display the current time compared to the total time(in that case, what about getting the total time as well), i’ve looked through every function, definition, etc., that “Mix_” is included in and i cant find an outright function that returns the current or total time, so im guessing i’ll have to go through a bit of a process to create a function that does that, but what are the first steps to doing that?

Hm, there may be something you could hack together using fields on the Mix_Music struct, but it kind of sounds like playing with fire.

An easier option that would probably work pretty well is just to keep track of the amount of time the music has been playing using your language’s canonical timing functionality. I’ve found this can be off by a few tenths of a second, maybe more or less from machine to machine, though.

The third option is to drop SDL_Mixer. It’s a great library, but SDL’s native audio functionality is incredibly flexible and not as hard as it looks, really. You could track the number of samples and convert it to seconds by dividing by your sample rate, and that would give you perfect accuracy.

Huh, i actually had no idea that SDL had any native audio functionality, is there any documentation or examples of this i can be directed to so i can get an idea of how to change my music player, and would it still be able to play both .mp3 and .ogg?

You’ll need to use wav for the built-in, though I hear SDL_Sound is a good library for loading other formats. I haven’t used it myself though.

But here is a pretty good tutorial that will at least point you in the right direction: Play a sound with SDL2 (no SDL_Mixer) · GitHub

I used it a while back when I was looking for more flexibility. In your case, you might consider keeping track of position in samples similarly to how the tutorial does with the audio_pos variable.

1 Like

Agreed. That’s what I use too; it does everything I want (and avoids all the nasty dependencies that SDL_Mixer has). But, yes, it means using WAV or linking in the codecs you need - I include dr_mp3.h which is a lightweight header-only library for MP3.