Audio.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
8#include <cstring>
9#include <iostream>
10#include <smk/Audio.hpp>
11#include <string>
12#include <vector>
13namespace smk {
14
15namespace {
16int g_ref_count = 0; // NOLINT
17ALCdevice* g_audio_device = nullptr; // NOLINT
18ALCcontext* g_audio_context = nullptr; // NOLINT
19
20void GetDevices(std::vector<std::string>& devices) {
21 devices.clear();
22 const ALCchar* device_list = alcGetString(nullptr, ALC_DEVICE_SPECIFIER);
23 if (!device_list) {
24 return;
25 }
26
27 while (std::strlen(device_list) > 0) {
28 devices.emplace_back(device_list);
29 device_list += std::strlen(device_list) + 1; // NOLINT
30 }
31}
32
33} // namespace
34
35Audio::Audio() {
36 if (g_ref_count++) {
37 return;
38 }
39 std::vector<std::string> devices;
40 GetDevices(devices);
41 std::cout << "Audio devices found " << devices.size() << ":" << std::endl;
42
43 for (auto& it : devices) {
44 std::cout << "* " << it << std::endl;
45 }
46
47 std::cout << std::endl;
48
49 g_audio_device = alcOpenDevice(devices[0].c_str());
50
51 if (!g_audio_device) {
52 std::cerr << "Failed to get an OpenAL device. Please check you have some "
53 "backend configured while building your application. For "
54 "instance PulseAudio with libpulse-dev"
55 << std::endl;
56 return;
57 }
58
59 g_audio_context = alcCreateContext(g_audio_device, nullptr);
60 if (!g_audio_context) {
61 std::cerr << "Failed to get an OpenAL context" << std::endl;
62 return;
63 }
64
65 if (!alcMakeContextCurrent(g_audio_context)) {
66 std::cerr << "Failed to make the OpenAL context active" << std::endl;
67 return;
68 }
69}
70
71Audio::~Audio() {
72 if (--g_ref_count) {
73 return;
74 }
75 // Destroy the context
76 alcMakeContextCurrent(nullptr);
77 if (g_audio_context) {
78 alcDestroyContext(g_audio_context);
79 g_audio_context = nullptr;
80 }
81
82 // Destroy the device
83 if (g_audio_device) {
84 alcCloseDevice(g_audio_device);
85 g_audio_device = nullptr;
86 }
87}
88
89/// @return true if there is at least one Audio class instanciated.
90// static
92 return g_ref_count;
93}
94
95} // namespace smk
static bool Initialized()
Definition: Audio.cpp:91