2023-06-11 19:17:50 +05:00
|
|
|
/*
|
|
|
|
|
Abandoned temporary.
|
|
|
|
|
Problems with blocking behaviour.
|
|
|
|
|
Possible fixes are running rodio in a separate thread or smthng.
|
|
|
|
|
*/
|
|
|
|
|
|
2025-12-11 23:43:50 +05:00
|
|
|
use once_cell::sync::OnceCell;
|
2023-06-11 19:17:50 +05:00
|
|
|
use std::fs::File;
|
|
|
|
|
use std::io::BufReader;
|
2025-12-11 23:43:50 +05:00
|
|
|
use std::path::PathBuf;
|
2023-06-11 19:17:50 +05:00
|
|
|
|
2025-12-12 01:59:07 +05:00
|
|
|
// use rodio::{Decoder, OutputStream, OutputStreamHandle, Sink};
|
|
|
|
|
use rodio::{Decoder, OutputStream, Sink};
|
2023-06-11 19:17:50 +05:00
|
|
|
|
|
|
|
|
// static STREAM: OnceCell<OutputStream> = OnceCell::new();
|
2025-12-12 01:59:07 +05:00
|
|
|
static STREAM_HANDLE: OnceCell<OutputStream> = OnceCell::new();
|
2023-06-11 19:17:50 +05:00
|
|
|
static SINK: OnceCell<Sink> = OnceCell::new();
|
|
|
|
|
|
|
|
|
|
pub fn init() -> Result<(), ()> {
|
2026-01-04 06:14:05 +05:00
|
|
|
if STREAM_HANDLE.get().is_some() {
|
2025-12-11 23:43:50 +05:00
|
|
|
return Ok(());
|
|
|
|
|
} // already initialized
|
2023-06-11 19:17:50 +05:00
|
|
|
|
|
|
|
|
// get output stream handle to the default physical sound device
|
2025-12-12 01:59:07 +05:00
|
|
|
match rodio::OutputStreamBuilder::open_default_stream() {
|
|
|
|
|
Ok(stream_handle) => {
|
2023-06-11 19:17:50 +05:00
|
|
|
// create sink
|
2025-12-12 01:59:07 +05:00
|
|
|
let sink = Sink::connect_new(&stream_handle.mixer());
|
|
|
|
|
info!("Sink initialized.");
|
2023-06-11 19:17:50 +05:00
|
|
|
|
|
|
|
|
// store
|
|
|
|
|
// STREAM.set(_stream).unwrap();
|
|
|
|
|
STREAM_HANDLE.set(stream_handle);
|
|
|
|
|
SINK.set(sink);
|
|
|
|
|
|
|
|
|
|
// success
|
|
|
|
|
Ok(())
|
2025-12-11 23:43:50 +05:00
|
|
|
}
|
2023-06-11 19:17:50 +05:00
|
|
|
Err(msg) => {
|
|
|
|
|
error!("Failed to initialize audio stream.\nError details: {}", msg);
|
|
|
|
|
|
|
|
|
|
// failed
|
|
|
|
|
Err(())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn play_sound(filename: &PathBuf, sleep: bool) {
|
|
|
|
|
// Load a sound from a file, using a path relative to Cargo.toml
|
|
|
|
|
// let filepath = format!("{PUBLIC_PATH}/sound/{filename}.wav");
|
|
|
|
|
let file = BufReader::new(File::open(&filename).unwrap());
|
|
|
|
|
|
|
|
|
|
// Decode that sound file into a source
|
|
|
|
|
let source = Decoder::new(file).unwrap();
|
|
|
|
|
|
|
|
|
|
// Play the sound directly on the device
|
|
|
|
|
// STREAM_HANDLE.get().unwrap().play_raw(source.convert_samples());
|
|
|
|
|
SINK.get().unwrap().append(source);
|
|
|
|
|
|
|
|
|
|
if sleep {
|
|
|
|
|
// The sound plays in a separate thread. This call will block the current thread until the sink
|
|
|
|
|
// has finished playing all its queued sounds.
|
|
|
|
|
SINK.get().unwrap().sleep_until_end();
|
|
|
|
|
}
|
2025-12-11 23:43:50 +05:00
|
|
|
}
|