Loading and Playing Audio
Audio files are loaded by creating an AudioFile object. This uses the following constructor:
Audio::AudioFile audioFile("sound.ogg");
Mach::GL currently supports the loading of .OGG and .MP3 files. Loading any other filetype will resulst in a error being thrown.
Then, a SoundSource object needs to be created using the following constructor:
Audio::MACH_SOUND_SOURCE source = Audio::SoundSource::createSoundSource(sourceProperties);
This constructor takes in a SoundSourceProperties object. This holds configurable properties about the SoundSource object. The properties consist of:
Property | Type | Defaults | Description |
---|---|---|---|
Pitch | float | 1.0f | Sets the pitch of the source |
Gain | float | 1.0f | Sets the gain of the source |
Position | float3 | (0,0,0) | Position for 3D audio |
Velocity | float3 | (0,0,0) | Velocity for moving 3D audio |
Loop | bool | false | Determines if the track will loop or play once |
A SoundBuffer object also has to be created, this can be thought of the queue of audio tracks to be played. If multiple tracks are to be played simultainiously, multiple buffers need to be created.
Audio::MACH_SOUND_BUFFER soundBuffer = Audio::SoundBuffer::createSoundBuffer();
AudioFile objects can be added to the queue by calling the function:
soundBuffer->addSoundEffect(audioFile);
To then play the audio file, call the function:
soundSource->play(audioFile.getBufferID());
Example Code:
#include "../MachGL/MachGL.h"
using namespace MachGL;
int main() {
uint32_t width = 1920;
uint32_t height = 1080;
MACH_WINDOW window = Window::createWindow("Window Title", width, height);
window->MSAA(4);
window->init();
//Loads the audio file, creates the sound source and buffer
Audio::AudioFile audioFile("sound.ogg");
Audio::SoundSourceProperties soundSourceProperties = {};
Audio::MACH_SOUND_BUFFER soundBuffer = Audio::SoundBuffer::createSoundBuffer();
Audio::MACH_SOUND_SOURCE soundSource = Audio::SoundSource::createSoundSource(soundSourceProperties);
//Adds the audio file to the buffer and then plays the sound source using the bufferID
soundBuffer->addSoundSource(audioFile);
soundSource->play(audioFile.getBufferID());
while (!window->closed()) {
window->clear();
window->update();
}
window->close();
return 0;
}