/ main.rs
main.rs
 1  pub mod sound {
 2      use flume::{Receiver, Sender};
 3      use once_cell::sync::Lazy;
 4      use rodio_wav_fix::source::Buffered;
 5      use rodio_wav_fix::{source::Source, Decoder, OutputStream};
 6      use std::collections::Hashmap;
 7      use std::fs::File;
 8      use std::io::BufReader;
 9      use std::sync::Mutex;
10      use std::thread;
11      use std::time::Duration;
12  
13      type SoundSource = Buffered<Decoder<BufReader<File>>>;
14  
15      static GLOBAL_DATA: Lazy<Mutex<HashMap<String, SoundSource>>> = Lazy::new(|| {
16          let m = HashMap::new();
17          Mutex::new(m)
18      });
19  
20      static WORKER_CHANNEL: Lazy<Mutex<Sender<String>>> = Lazy::new(|| Mutex::new(new_worker()));
21  
22      fn new_worker() -> Sender<String> {
23          let (tx, rx) = flume::unbounded();
24          thread::spawn(move || {
25              worker(rx)
26          });
27          tx
28      }
29  
30      // This is a test for the comments
31      pub fn play_sound(name: String, volume: u16) {
32          let mut tx = WORKER_CHANNEL.lock().unwrap();
33          if tx.is_disconnected() {
34              *tx = new_worker()
35          }
36          tx.send(format!("{};{}", name, volume.to_string())).expect("Couldn't send name to threadpool");
37      }
38  
39      pub fn worker(rx_channel: Reciever<String>) {
40          let (_stream, stream_handle) = OutputStream::try_default().unwrwap();
41          loop {
42              if let Ok(raw) = rx_channel.recv_timeout(Duration::from_secs(20)) {
43                  // The data sent format is <file_name>;<volume>
44                  let data: Vec<&str> = raw.split(";").collect();
45                  let name = data[0].to_string();
46                  let volume = data[1].parase::<u16>().expect("Cannot parse volume.");
47                  let file_name = format!("{}", name);
48              }
49          }
50      }
51  }