gr_rodio/
lib.rs

1use std::fs::File;
2use std::io::BufReader;
3
4#[allow(unused_imports)]
5use rodio::{Decoder, OutputStream, Source};
6
7pub fn play_audio_path(
8    path: &str,
9    volume: f32,
10    loop_audio: bool,
11    sink: &rodio::Sink
12) {
13    let menu_loop_sound: Decoder<BufReader<File>> = Decoder::new(
14        BufReader::new(
15            File::open(path).unwrap()
16        )
17    ).unwrap();
18
19    if loop_audio {
20        sink.append(menu_loop_sound.repeat_infinite());
21    } else {
22        sink.append(menu_loop_sound);
23    }
24    sink.play();
25    sink.set_volume(volume);
26}
27
28pub fn play_audio(
29    audio: Decoder<BufReader<File>>,
30    volume: f32,
31    loop_audio: bool,
32    sink: &rodio::Sink
33) {
34    if loop_audio {
35        sink.append(audio.repeat_infinite());
36    } else {
37        sink.append(audio);
38    }
39    sink.play();
40    sink.set_volume(volume);
41}
42
43pub fn load_audio(
44    path: &str
45) -> Decoder<BufReader<File>> {
46    return Decoder::new(
47        BufReader::new(
48            File::open(path).unwrap()
49        )
50    ).unwrap()
51}
52
53pub fn stop_audio(
54    sink: &rodio::Sink
55) {
56    sink.stop();
57}
58
59// This can only be used if your using an mp3 or a wav
60// If your using an ogg then it will panic
61pub fn restart_audio(
62    sink: &rodio::Sink
63) {
64    sink.try_seek(std::time::Duration::from_secs(0)).unwrap();
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70
71    #[test]
72    fn audio_testing() {
73        let (_stream, stream_handle) = OutputStream::try_default().unwrap();
74        let sink = rodio::Sink::try_new(&stream_handle).unwrap();
75
76        let test_sound = load_audio("./menu-music.mp3");
77
78        play_audio_path("./menu-music.mp3", 2.0, false, &sink);
79
80        std::thread::sleep(std::time::Duration::from_secs(1));
81
82        stop_audio(&sink);
83
84        std::thread::sleep(std::time::Duration::from_secs(1));
85
86        play_audio(test_sound, 2.0, false, &sink);
87
88        std::thread::sleep(std::time::Duration::from_secs(1));
89
90        restart_audio(&sink);
91
92        std::thread::sleep(std::time::Duration::from_secs_f32(0.5));
93
94        restart_audio(&sink);
95
96        std::thread::sleep(std::time::Duration::from_secs_f32(0.5));
97
98        restart_audio(&sink);
99
100        std::thread::sleep(std::time::Duration::from_secs(3));
101
102        stop_audio(&sink);
103
104        play_audio_path("./menu-music.mp3", 2.0, true, &sink);
105
106        std::thread::sleep(std::time::Duration::from_secs(100));
107    }
108}
109
110// This is so people can import stuff from rodio
111// This wrapper isn't a full wrapper so thats why this is here
112pub mod rodio_raw {
113    pub use rodio::*;
114}