Le Bagage, Gautier Pelloux-Prayer

You are here:   Home > Welcome > OpenAL - start track not at origin (seek pos)

OpenAL - start track not at origin (seek pos)

  • Issue : how to start a track not at the beginning but at a given time (in seconds or bytes) ?
  • Solution
    1. moveToSeek(ALfloat seek) (seek 0-start et 1-end of track) will start at 100*seek% total length of the track (eg. seek=0.5, we'll start at half of the track)
    2. moveToSec(ALfloat start) starts at start seconds from start
    3. getBufferLengthInSec() return total size in seconds of track in buffe
ALuint playFromSeek(ALuint source, ALuint buffer, ALfloat seek) { 
  if (seek < 0 || seek > 1) return; //stopping if seek is invalid
  alSourcei(source, AL_BUFFER, buffer); //retrieving source's buffer
  ALint tot = 0;
  alGetBufferi(buffer, AL_SIZE, &tot); //size of buffer (in bytes)
  alSourcei(source, AL_BYTE_OFFSET, seek*tot); //positionning...
  alSourcePlay(source); //let's play
  return source;
}
void playFromSec(ALuint source, ALuint buffer, ALfloat sec) {
  //that's just a seek pos defined by sec / (total size in sec)
  playFromSeek(source, buffer, sec/getBufferLengthInSec(buffer));
}
ALfloat getBufferLengthInSec(ALuint buffer) {
  ALint size, bits, channels, freq;
  alGetBufferi(buffer, AL_SIZE, &size);
  alGetBufferi(buffer, AL_BITS, &bits);
  alGetBufferi(buffer, AL_CHANNELS, &channels);
  alGetBufferi(buffer, AL_FREQUENCY, &freq);
  if(alGetError() != AL_NO_ERROR) return -1.0f;
  return (ALfloat)((ALuint)size/channels/(bits/8)) / (ALfloat)freq;
}