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
use std::fmt::{Debug, Formatter, Result as FmtResult};
use std::io::Cursor;
use cpal::OutputDevices;
use rodio::{default_output_device, output_devices, Decoder, Device, Sink, Source as RSource};
use DecoderError;
use source::Source;
#[derive(Clone, Eq, PartialEq)]
pub struct Output {
pub(crate) device: 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()
}
}
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(),
}
}