How to find the last possible position of a sample instance

Is it possible to find the last possible position of a sample instance?

My brute force method is to have the program output al_get_sample_instance_position(instance) every tick and then listen to the instance to completion, however I can't help but feel like there is a more elegant way to get this in the code. Is there?

Edgar Reynaldo

al_get_sample_length should do what you want if you want the number of samples. If you want the duration of a sample in seconds, you'll need to divide by al_get_sample_frequency and perhaps al_get_sample_channels, converting it to a channel count first.


al_get_sample_instance_length() is actually tremendously helpful, thanks! What's weird, though, is that when I use my brute force method and compare it to al_get_sample_instance_position(), I get a value that is less than my brute force output.

I'm trying to get a song to loop back on itself, but it has an intro. So I'm trying to play the intro and then get the main looping part of the song to play immediately after, seamlessly. The problem is that I am not aware of a way to track when the song is finished playing to tell this thing to loop, and I thought that if I could know the length I could nail it that way. This works somewhat, except that I am getting different values when I play the song. I can't begin to postulate what this means, but it does create a conundrum for me.

Edgar Reynaldo

Get the duration of the sample as I suggested earlier and use a timer, or otherwise call al_get_sample_instance_playing repeatedly until it returns false.

Bruce Perry

You could use an audio stream and feed the sample data to it manually, thereby eliminating the glitch? It might not lead to the best performance possible, but it will sound perfect.

Trying to use CPU timing or system clock timing to place an audio sample will always be imperfect. It's much better if you can specify the exact position in the output stream that the sample should start (which you can do if you're feeding the data to a stream yourself).

Or does Allegro have a 'play something at a scheduled instant in the audio output' feature? Could one be added?


Maybe you could also use al_set_audio_stream_loop_secs directly to set the stream's loop points, if you use audio streams via al_load_audio_stream()


Edgar's idea worked perfectly for what I was trying to do. I should have known better, but for some reason I was under the impression that the playing property wouldn't get kicked to false once it stopped playing.

Monitoring that and throwing a bool around helped me get everything taken care of. Thanks so much for the help!

For the sake of time, this seems like the best option, and then once I no longer have due dates on this project, I can experiment with some of the other ideas you all have thrown around to see what I can do about optimization.

Thread #616720. Printed from