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
use std::fmt;
use std::path;
use sdl2;
use sdl2::mixer::LoaderRWops;
use context::Context;
use util;
use GameError;
use GameResult;
pub type Channel = sdl2::mixer::Channel;
pub trait AudioOps {
fn new_channel() -> Channel;
fn play_sound(&self, sound: &Sound) -> GameResult<Channel>;
fn pause(&self);
fn stop(&self);
fn resume(&self);
fn rewind(&self);
}
pub struct Sound {
chunk: sdl2::mixer::Chunk,
}
impl Sound {
pub fn new<P: AsRef<path::Path>>(context: &mut Context, path: P) -> GameResult<Sound> {
let path = path.as_ref();
let mut buffer: Vec<u8> = Vec::new();
let rwops = try!(util::rwops_from_path(context, path, &mut buffer));
let chunk = try!(rwops.load_wav());
Ok(Sound { chunk: chunk })
}
pub fn play(&self) -> GameResult<Channel> {
let channel = sdl2::mixer::channel(-1);
channel.play(&self.chunk, 0)
.map_err(GameError::from)
}
}
impl fmt::Debug for Sound {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<Sound: {:p}>", self)
}
}
impl AudioOps for Channel {
fn new_channel() -> Channel {
sdl2::mixer::channel(-1)
}
fn play_sound(&self, sound: &Sound) -> GameResult<Channel> {
let channel = self;
channel.play(&sound.chunk, 0)
.map_err(GameError::from)
}
fn pause(&self) {
Channel::pause(*self)
}
fn stop(&self) {
self.halt()
}
fn resume(&self) {
Channel::resume(*self)
}
fn rewind(&self) {
if let Some(chunk) = self.get_chunk() {
self.stop();
let _ = self.play(&chunk, 0);
}
}
}
pub struct Music {
music: sdl2::mixer::Music,
}
impl Music {
pub fn new<P: AsRef<path::Path>>(context: &mut Context, path: P) -> GameResult<Music> {
let path = path.as_ref();
let mut buffer: Vec<u8> = Vec::new();
let rwops = try!(util::rwops_from_path(context, path, &mut buffer));
let music = try!(rwops.load_music());
Ok(Music { music: music })
}
}
impl fmt::Debug for Music {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<Music: {:p}>", self)
}
}
pub fn play_music_times(music: &Music, n: i32) -> GameResult<()> {
music.music
.play(n)
.map_err(GameError::from)
}
pub fn play_music(music: &Music) -> GameResult<()> {
play_music_times(music, -1)
}
pub fn pause_music() {
sdl2::mixer::Music::pause()
}
pub fn resume_music() {
sdl2::mixer::Music::resume()
}
pub fn stop_music() {
sdl2::mixer::Music::halt()
}
pub fn rewind_music() {
sdl2::mixer::Music::rewind()
}