|
| 1 | +#include "audio.hh" |
| 2 | + |
| 3 | + |
| 4 | +namespace SDL { |
| 5 | + Audio::Audio( |
| 6 | + const SDL_AudioSpec audio_spec, |
| 7 | + Uint8* audio_buffer, |
| 8 | + const Uint32 audio_length, |
| 9 | + std::function<void(Uint8*)> free, |
| 10 | + unsigned char volume |
| 11 | + ) { |
| 12 | + this->audio_spec = audio_spec; |
| 13 | + this->audio_buffer = audio_buffer; |
| 14 | + this->audio_length = audio_length; |
| 15 | + this->free = free; |
| 16 | + this->volume = volume; |
| 17 | + // TODO: Callback |
| 18 | + } |
| 19 | + |
| 20 | + AudioInstance Audio::play(const bool start_automatically) { |
| 21 | + return AudioInstance(*this, 1, start_automatically); |
| 22 | + } |
| 23 | + |
| 24 | + AudioInstance Audio::loop(const size_t times, const bool start_automatically) { |
| 25 | + return AudioInstance(*this, times, start_automatically); |
| 26 | + } |
| 27 | + |
| 28 | + AudioInstance Audio::loop(const bool start_automatically) { |
| 29 | + return AudioInstance(*this, 0, start_automatically); |
| 30 | + } |
| 31 | + |
| 32 | + Audio Audio::load_wav(const std::string file) { |
| 33 | + SDL_AudioSpec audio_spec; |
| 34 | + Uint8* audio_buffer; |
| 35 | + Uint32 audio_length; |
| 36 | + SDL_LoadWAV(file.c_str(), &audio_spec, &audio_buffer, &audio_length); |
| 37 | + return Audio(audio_spec, audio_buffer, audio_length, SDL_FreeWAV); |
| 38 | + } |
| 39 | + |
| 40 | + Audio::~Audio() { |
| 41 | + this->free(this->audio_buffer); |
| 42 | + } |
| 43 | + |
| 44 | + void AudioInstance::new_device() { |
| 45 | + this->device = SDL_OpenAudioDevice( |
| 46 | + NULL, |
| 47 | + 0, |
| 48 | + &this->source.audio_spec, |
| 49 | + NULL, |
| 50 | + SDL_AUDIO_ALLOW_FORMAT_CHANGE |
| 51 | + ); |
| 52 | + } |
| 53 | + |
| 54 | + AudioInstance::AudioInstance(Audio& audio, const size_t loop, const bool start) |
| 55 | + : source(audio) { |
| 56 | + this->loop = loop; |
| 57 | + this->new_device(); |
| 58 | + if (start) |
| 59 | + this->play(); |
| 60 | + else |
| 61 | + this->pause(); |
| 62 | + } |
| 63 | + |
| 64 | + void AudioInstance::pause() { |
| 65 | + SDL_PauseAudioDevice(this->device, 1); |
| 66 | + } |
| 67 | + |
| 68 | + void AudioInstance::stop() { |
| 69 | + SDL_CloseAudioDevice(this->device); |
| 70 | + this->new_device(); |
| 71 | + } |
| 72 | + |
| 73 | + void AudioInstance::play() { |
| 74 | + SDL_PauseAudioDevice(this->device, 0); |
| 75 | + } |
| 76 | +} |
0 commit comments