1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
use std::{
fmt::{Debug, Formatter, Result as FmtResult},
io::Cursor,
};
use cpal::OutputDevices;
use log::error;
use rodio::{default_output_device, output_devices, Decoder, Device, Sink, Source as RSource};
use amethyst_core::ecs::World;
use crate::{sink::AudioSink, source::Source, DecoderError};
#[derive(Clone, Eq, PartialEq)]
pub struct Output {
pub(crate) device: Device,
}
impl Default for Output {
fn default() -> Self {
default_output_device()
.map(|re| Output { device: re })
.expect("No default output device")
}
}
impl Output {
pub fn name(&self) -> String {
self.device.name()
}
pub fn try_play_once(&self, source: &Source, volume: f32) -> Result<(), DecoderError> {
self.try_play_n_times(source, volume, 1)
}
pub fn play_once(&self, source: &Source, volume: f32) {
self.play_n_times(source, volume, 1);
}
pub fn play_n_times(&self, source: &Source, volume: f32, n: u16) {
if let Err(err) = self.try_play_n_times(source, volume, n) {
error!("An error occurred while trying to play a sound: {:?}", err);
}
}
pub fn try_play_n_times(
&self,
source: &Source,
volume: f32,
n: u16,
) -> Result<(), DecoderError> {
let sink = Sink::new(&self.device);
for _ in 0..n {
sink.append(
Decoder::new(Cursor::new(source.clone()))
.map_err(|_| DecoderError)?
.amplify(volume),
);
}
sink.detach();
Ok(())
}
}
impl Debug for Output {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
f.debug_struct("Output")
.field("device", &self.name())
.finish()
}
}
#[allow(missing_debug_implementations)]
pub struct OutputIterator {
input: OutputDevices,
}
impl Iterator for OutputIterator {
type Item = Output;
fn next(&mut self) -> Option<Output> {
self.input.next().map(|re| Output { device: re })
}
}
pub fn default_output() -> Option<Output> {
default_output_device().map(|re| Output { device: re })
}
pub fn outputs() -> OutputIterator {
OutputIterator {
input: output_devices(),
}
}
pub fn init_output(world: &mut World) {
if let Some(o) = default_output() {
world
.entry::<AudioSink>()
.or_insert_with(|| AudioSink::new(&o));
world.entry::<Output>().or_insert_with(|| o);
} else {
error!("Failed finding a default audio output to hook AudioSink to, audio will not work!")
}
}
#[cfg(test)]
mod tests {
#[cfg(target_os = "linux")]
use {
crate::{output::Output, source::Source, DecoderError},
amethyst_utils::app_root_dir::application_root_dir,
std::{fs::File, io::Read, vec::Vec},
};
#[test]
#[cfg(target_os = "linux")]
fn test_play_wav() {
test_play("tests/sound_test.wav", true)
}
#[test]
#[cfg(target_os = "linux")]
fn test_play_mp3() {
test_play("tests/sound_test.mp3", true);
}
#[test]
#[cfg(target_os = "linux")]
fn test_play_flac() {
test_play("tests/sound_test.flac", true);
}
#[test]
#[cfg(target_os = "linux")]
fn test_play_ogg() {
test_play("tests/sound_test.ogg", true);
}
#[test]
#[cfg(target_os = "linux")]
fn test_play_fake() {
test_play("tests/sound_test.fake", false);
}
#[cfg(target_os = "linux")]
fn test_play(file_name: &str, should_pass: bool) {
let app_root = application_root_dir().unwrap();
let audio_path = app_root.join(file_name);
let mut f = File::open(audio_path).unwrap();
let mut buffer = Vec::new();
f.read_to_end(&mut buffer).unwrap();
let src = Source { bytes: buffer };
let vol: f32 = 4.0;
let n: u16 = 5;
let output = Output::default();
output.play_once(&src, vol);
output.play_n_times(&src, vol, n);
let result_try_play_once = output.try_play_once(&src, vol);
check_result(result_try_play_once, should_pass);
let result_try_play_n_times = output.try_play_n_times(&src, vol, n);
check_result(result_try_play_n_times, should_pass);
}
#[cfg(target_os = "linux")]
fn check_result(result: Result<(), DecoderError>, should_pass: bool) {
match result {
Ok(_pass) => assert!(
should_pass,
"Expected `play` result to be Err(..), but was Ok(..)"
),
Err(fail) => assert!(
!should_pass,
"Expected `play` result to be `Ok(..)`, but was {:?}",
fail
),
};
}
}