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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
use crate::errors::{MelodyErrors, MelodyErrorsKind};
use crate::song::{Playlist, Song};
use crate::utils::fmt_duration;
use rand::seq::SliceRandom;
use rand::thread_rng;
use rodio;
use std::fmt;
use std::fs::File;
use std::io::{BufReader, Write};
use tabwriter::TabWriter;
#[derive(Clone, Debug)]
pub enum MusicPlayerStatus {
Stopped(Option<Song>),
NowPlaying(Song),
Paused(Song),
}
impl fmt::Display for MusicPlayerStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use crate::MusicPlayerStatus::*;
match self.clone() {
Paused(song) => write!(f, "[Paused] : {} @ {}", song, fmt_duration(&song.elapsed())),
NowPlaying(song) => write!(f, "[Now Playing] : {}", song),
Stopped(s) => match s {
Some(song) => write!(f, "[Stopped] : Last Played - {}", song),
None => write!(f, "[Stopped]"),
},
}
}
}
#[allow(missing_debug_implementations)]
pub struct MusicPlayer {
playlist: Vec<Song>,
sink: rodio::Sink,
current: Option<Song>,
previous: Option<Song>,
}
impl MusicPlayer {
pub fn new(playlist: Playlist) -> Self {
let endpoint =
rodio::default_output_device().expect("Failed to find default music endpoint");
MusicPlayer {
playlist: playlist.tracks,
sink: rodio::Sink::new(&endpoint),
current: None,
previous: None,
}
}
pub fn shuffle(&mut self) {
self.playlist.shuffle(&mut thread_rng());
}
pub fn start(&mut self) -> Result<(), MelodyErrors> {
if self.playlist.is_empty() {
Err(MelodyErrors::new(
MelodyErrorsKind::EmptyQueue,
"Playlist is empty",
None,
))
} else {
if self.sink.empty() {
let mut current = self.playlist.remove(0);
let file = File::open(¤t)
.unwrap_or_else(|_| panic!("Failed to read {:#?}", current.file));
let source = rodio::Decoder::new(BufReader::new(file))
.unwrap_or_else(|_| panic!("Failed to decode {:#?}", current.file));
self.sink.append(source);
current.resume();
self.current = Some(current);
};
Ok(())
}
}
pub fn resume(&mut self) {
self.sink.play();
self.current = self.current.take().and_then(|mut s| {
s.resume();
Some(s)
});
}
pub fn pause(&mut self) {
self.sink.pause();
self.current = self.current.take().and_then(|mut s| {
s.stop();
Some(s)
});
}
pub fn stop(&mut self) {
self.sink.stop();
self.previous = self.current.take().and_then(|mut s| {
s.stop();
Some(s)
});
}
pub fn play_next(&mut self) {
let vol = self.sink.volume();
self.stop();
let endpoint =
rodio::default_output_device().expect("Failed to find default music endpoint");
self.sink = rodio::Sink::new(&endpoint);
self.sink.set_volume(vol);
let _ = self.start().is_ok();
}
pub fn volume(&self) -> f32 {
self.sink.volume()
}
pub fn set_volume(&mut self, volume: f32) {
self.sink.set_volume(volume)
}
pub fn lock(&self) {
self.sink.sleep_until_end();
}
pub fn queue(&self) -> &Vec<Song> {
&self.playlist
}
pub fn status(&self) -> MusicPlayerStatus {
if self.sink.empty() {
MusicPlayerStatus::Stopped(self.previous.clone())
} else if let Some(song) = self.current.clone() {
if self.sink.is_paused() {
MusicPlayerStatus::Paused(song)
} else {
MusicPlayerStatus::NowPlaying(song)
}
} else {
MusicPlayerStatus::Stopped(self.previous.clone())
}
}
pub fn quit(mut self) {
self.stop();
self.playlist = vec![];
}
}
impl fmt::Display for MusicPlayer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let now_playing = match self.current {
Some(ref song) => {
let status: &str = if self.sink.is_paused() {
"[paused] "
} else {
""
};
format!("{}{}\n", status, song)
}
None => String::new(),
};
let mut tw = TabWriter::new(Vec::new());
let mut lines: Vec<String> = vec![String::from(
"|\tArtist\t|\tAlbum\t|\tTitle\t|\tDuration\t|",
)];
for track in &self.playlist {
let duration = fmt_duration(&track.duration);
lines.push(format!(
"|\t{}\t|\t{}\t|\t{}\t|\t{}\t|",
track.artist().unwrap_or("Unknown Artist"),
track.album().unwrap_or("Unknown Album"),
track.title().unwrap_or("Unknown Title"),
duration
))
}
write!(tw, "{}", lines.join("\n")).unwrap();
tw.flush().unwrap();
write!(
f,
"{}{}",
now_playing,
String::from_utf8(tw.into_inner().unwrap()).unwrap()
)
}
}
impl Drop for MusicPlayer {
fn drop(&mut self) {
self.sink.stop()
}
}
#[allow(missing_debug_implementations)]
pub struct MinimalMusicPlayer {
sink: ::rodio::Sink,
now_playing: Option<Song>,
prev: Option<Song>,
songs: Box<dyn Iterator<Item = Song>>,
}
impl Default for MinimalMusicPlayer {
fn default() -> Self {
let device = rodio::default_output_device().unwrap();
let v: Vec<Song> = Vec::with_capacity(0);
Self {
sink: ::rodio::Sink::new(&device),
now_playing: None,
prev: None,
songs: Box::new(v.into_iter()),
}
}
}
impl MinimalMusicPlayer {
pub fn set_volume(&mut self, volume: f32) {
self.sink.set_volume(volume)
}
pub fn sleep_until_end(&self) {
self.sink.sleep_until_end()
}
pub fn consume<I: 'static + Iterator<Item = Song>>(iter: I) -> Self {
Self {
songs: Box::new(iter),
..Default::default()
}
}
pub fn is_playing(&self) -> bool {
!self.sink.empty()
}
pub fn pause(&mut self) {
self.sink.pause()
}
pub fn resume(&mut self) {
self.sink.play()
}
pub fn stop(&mut self) {
self.sink.stop();
}
pub fn volume(&self) -> f32 {
self.sink.volume()
}
}
impl Iterator for MinimalMusicPlayer {
type Item = Song;
fn next(&mut self) -> Option<Song> {
let vol = self.sink.volume();
self.sink.stop();
let device = rodio::default_output_device().unwrap();
if let Some(song) = self.songs.next() {
if let Ok(f) = File::open(&song) {
if let Ok(s) = rodio::Decoder::new(BufReader::new(f)) {
self.sink = rodio::Sink::new(&device);
self.sink.set_volume(vol);
self.prev = self.now_playing.replace(song);
self.sink.append(s);
}
}
} else {
self.now_playing = None;
}
self.now_playing.as_ref().cloned()
}
}
impl ::std::iter::IntoIterator for Playlist {
type Item = Song;
type IntoIter = MinimalMusicPlayer;
fn into_iter(self) -> MinimalMusicPlayer {
let device = rodio::default_output_device().unwrap();
MinimalMusicPlayer {
sink: rodio::Sink::new(&device),
prev: None,
now_playing: None,
songs: Box::new(self.tracks.into_iter()),
}
}
}