Duration of a loaded WAV file.

I am trying to find a way to get the duration of an WAV audio file loaded in SDL library.
I am using the latest official build of SDL for Windows, 64-bit, version 2.26.5.

The question is simple: how do I get the length in seconds, or simply – the duration of a file loaded with SDL_LoadWAV function ?

More details of the question are available here:

Thank you.

The audio_len output parameter is the length of the loaded audio buffer in bytes, not the size of the file. When dealing with audio buffers, SDL generally specifies the size in bytes.

So the steps to convert to seconds are pretty simple: divide the buffer length by the sample size to get the number of samples across all channels. Then divide by the number of channels to get the length of the audio clip in samples. Then divide that by the frequency to get the length in seconds.

Untested code:

double howManySeconds(const char *filename) {
	SDL_AudioSpec spec;
	uint32_t audioLen;
	uint8_t *audioBuf;
	double seconds = 0.0;

	if(SDL_LoadWAV(filename, &spec, &audioBuf, &audioLen) != NULL) {
		// we aren't using the actual audio in this example
		uint32_t sampleSize = SDL_AUDIO_BITSIZE(spec.format) / 8;
		uint32_t sampleCount = audioLen / sampleSize;
		// could do a sanity check and make sure (audioLen % sampleSize) is 0
		uint32_t sampleLen = 0;
		if(spec.channels) {
			sampleLen = sampleCount / spec.channels;
		} else {
			// spec.channels *should* be 1 or higher, but just in case
			sampleLen = sampleCount;
		seconds = (double)sampleLen / (double)audioSpec.freq;
	} else {
		// uh-oh!
		fprintf(stderr, "ERROR: can't load: %s: %s\n", filename, SDL_GetError());

	return seconds;

Thank you for the algorithm !

1 Like