SoundBuffer.cpp
1// Copyright 2019 Arthur Sonzogni. All rights reserved.
2// Use of this source code is governed by the MIT license that can be found in
3// the LICENSE file.
4
5#include <AL/al.h>
6#include <AL/alc.h>
7#include <libnyquist/Decoders.h>
8
9#include <algorithm>
10#include <iostream>
11#include <smk/Audio.hpp>
12#include <smk/SoundBuffer.hpp>
13#include <vector>
14
15namespace smk {
16
17SoundBuffer::SoundBuffer() = default;
18
19/// @brief Load a sound resource into memory from a file.
20SoundBuffer::SoundBuffer(const std::string& filename) : SoundBuffer() {
21 if (!Audio::Initialized()) {
22 static bool once = true;
23 if (once) {
24 std::cerr
25 << "Error: smk::Audio has not been initialized. Please create a "
26 "smk::Audio instance in the main() function before creating a "
27 "smk::SoundBuffer"
28 << std::endl;
29 once = false;
30 }
31 }
32
33 nqr::AudioData fileData;
34 nqr::NyquistIO loader;
35 loader.Load(&fileData, filename);
36
37 auto sample_rate = static_cast<ALsizei>(fileData.sampleRate);
38
39 std::vector<ALshort> data;
40 for (auto& it : fileData.samples) {
41 it = std::min(it, +1.f);
42 it = std::max(it, -1.f);
43 data.push_back(ALshort(it * float((1 << 15) - 1))); // NOLINT
44 }
45
46 ALenum format = {};
47 switch (fileData.channelCount) {
48 case 1:
49 format = AL_FORMAT_MONO16;
50 break;
51 case 2:
52 format = AL_FORMAT_STEREO16;
53 break;
54 default:
55 std::cerr << "SoundBuffer: Unsupported format file " + filename
56 << std::endl;
57 return;
58 }
59
60 alGenBuffers(1, &buffer_);
61 alBufferData(buffer_, format, data.data(),
62 ALsizei(data.size() * sizeof(ALshort)), sample_rate);
63
64 if (alGetError() != AL_NO_ERROR) {
65 std::cerr << "SoundBuffer: OpenAL error" << std::endl;
66 return;
67 }
68}
69
70SoundBuffer::~SoundBuffer() {
71 if (buffer_) {
72 alDeleteBuffers(1, &buffer_);
73 }
74}
75
76SoundBuffer::SoundBuffer(SoundBuffer&& o) noexcept {
77 this->operator=(std::move(o));
78}
79
80SoundBuffer& SoundBuffer::operator=(SoundBuffer&& o) noexcept {
81 std::swap(buffer_, o.buffer_);
82 return *this;
83}
84
85unsigned int SoundBuffer::buffer() const {
86 return buffer_;
87}
88
89} // namespace smk
static bool Initialized()
Definition: Audio.cpp:91
A sound file loaded in memory.
Definition: SoundBuffer.hpp:33