Play a sound#
Goal: load an audio file from disk and start it playing.
This tutorial walks through Demo00_PlaySound, the simplest libYSE
program. By the end you will have a sound playing, with hot keys to toggle,
play, pause, and stop it.
Source: Demo00_PlaySound.cpp.
Loading the sound#
A YSE::sound is an instance — one object per voice you want in the
scene. Load a file with create:
// load a sound in memory
sound.create(YSE_TEST_RESOURCES_DIR "/drone.ogg", nullptr, true);
// false on validation means the sound could not be loaded
if (!sound.isValid()) {
std::cout << "sound 'drone.ogg' not found" << std::endl;
}
The third argument is the loop flag; the demo loops the drone for as long
as it plays. The path is resolved relative to the working directory, so
the demo must be launched from build/bin/.
isValid() returns false if the file could not be opened or
decoded — always check it after create and fail fast.
Controlling playback#
Four methods cover the basics:
void DemoPlaySound::ToggleSound()
{
sound.toggle();
}
void DemoPlaySound::PlaySound()
{
sound.play();
}
void DemoPlaySound::StopSound()
{
sound.stop();
}
void DemoPlaySound::PauseSound()
{
sound.pause();
}
play()— start playback. Starts immediately, or queues if the sound is still loading.pause()— freeze the playhead. The nextplay()resumes from there.stop()— halt and rewind to the start of the source.toggle()— cycleplaying → paused,paused → playing,stopped → playing. Handy for one-key mappings.
What you learned#
One
YSE::soundinstance per playing voice.create(path, channel, loop)— the third arg is loop, leavechannelasnullptrto useMainMix.isValid()is the safety check aftercreate.play/pause/stop/toggleare the playback primitives.
Next#
Volume, pitch, and looping — set volume, pitch, and looping at runtime.
3D positioning — place the sound in 3D space.
YSE::sound— full API reference for the sound class.