Volume, pitch, and looping#
Goal: control a sound’s volume and playback speed at runtime.
Building on Play a sound, this tutorial walks through
Demo01_SoundProperties: load a sound, then change its level and pitch
on the fly.
Source: Demo01_SoundProperties.cpp.
Volume#
volume() is overloaded — call it with no arguments to read, with a
value to set.
void DemoSoundProperties::IncVolume()
{
sound.volume(sound.volume() + 0.1f);
}
void DemoSoundProperties::DecVolume()
{
sound.volume(sound.volume() - 0.1f);
}
The value is a linear gain in [0.0, 1.0]. volume(value, time) also
exists and fades over time milliseconds — much friendlier than the
default instant change for runtime gain riding.
Playback speed#
speed() controls both pitch and playback rate together — there is no
independent pitch-shift in libYSE. Doppler effect from listener / source
velocity layers on top of this unless doppler(false) is set.
void DemoSoundProperties::IncSpeed()
{
sound.speed(sound.speed() + 0.1f);
}
void DemoSoundProperties::DecSpeed()
{
sound.speed(sound.speed() - 0.1f);
}
1.0is the natural speed (and pitch).2.0is one octave up,0.5is one octave down.Negative values play backwards (not supported for streaming sounds).
Looping#
The third argument to sound::create is the loop flag. The demo passes
true because the test asset is short:
// load a sound in memory
sound.create(YSE_TEST_RESOURCES_DIR "/contact.ogg", nullptr, true);
Toggle it at runtime with sound::looping(bool).
What you learned#
volume(value)sets,volume()reads. Usevolume(value, time)to fade.speed(value)changes pitch and playback rate together.The
createloop flag enables looping at load time;looping(bool)toggles it later.
Next#
3D positioning — place the sound in 3D space.
Channels — group sounds for shared volume control.
YSE::sound— full sound API.