Compare commits

...

3 commits

Author SHA1 Message Date
Yash Karandikar 07198829cf oops 2022-10-06 16:12:07 -05:00
Yash Karandikar 884b23c5a5 Minor fixes 2022-10-06 16:09:53 -05:00
Yash Karandikar b891ff76b4 Use proper error handling and not unwrap() 2022-10-06 16:08:59 -05:00
2 changed files with 29 additions and 14 deletions

View file

@ -90,6 +90,7 @@
clippy::module_name_repetitions,
clippy::missing_errors_doc
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
pub mod physics;
pub mod vec2;
@ -107,9 +108,6 @@ use sdl2::{
video::{Window, WindowBuildError, WindowContext},
EventPump, IntegerOrSdlError,
};
use std::fs::File;
use std::io::BufReader;
use std::thread;
use std::{
cell::Cell,
ops::{Deref, DerefMut},
@ -165,6 +163,14 @@ error_from_format! {
InitError
}
#[cfg(feature = "audio")]
error_from_format! {
rodio::StreamError,
std::io::Error,
rodio::decoder::DecoderError,
rodio::PlayError
}
impl std::fmt::Display for CatboxError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
@ -774,24 +780,34 @@ impl Game {
}
}
#[cfg(feature = "audio")]
#[cfg_attr(docsrs, doc(cfg(feature = "audio")))]
/// Plays an audio file given the path of file and plays it for y seconds
/// ```no_run
/// # use cat_box::play;
/// play("/path/to/song.mp3", 15);
/// ```
#[cfg(feature = "audio")]
pub fn play<P: AsRef<Path> + std::marker::Send + 'static>(x: P, y: u64) -> thread::JoinHandle<()> {
pub fn play<P: AsRef<Path> + Send + 'static>(
path: P,
time: u64,
) -> std::thread::JoinHandle<Result<()>> {
use std::fs::File;
use std::io::BufReader;
use std::thread;
thread::spawn(move || {
let (_stream, stream_handle) = OutputStream::try_default().unwrap();
let (_stream, stream_handle) = OutputStream::try_default()?;
// Load a sound from a file, using a path relative to Cargo.toml
let file = BufReader::new(File::open(x).unwrap());
let file = BufReader::new(File::open(path)?);
// Decode that sound file into a source
let source = Decoder::new(file).unwrap();
let source = Decoder::new(file)?;
// Play the sound directly on the device
stream_handle.play_raw(source.convert_samples()).unwrap();
stream_handle.play_raw(source.convert_samples())?;
// The sound plays in a separate audio thread,
// so we need to keep the main thread alive while it's playing.
std::thread::sleep(std::time::Duration::from_secs(y));
std::thread::sleep(std::time::Duration::from_secs(time));
Ok(())
})
}

View file

@ -1,8 +1,6 @@
#![warn(clippy::pedantic)]
use cat_box::{
draw_text, get_keyboard_state, get_mouse_state, play, Game, Sprite, SpriteCollection,
};
use cat_box::{draw_text, get_keyboard_state, get_mouse_state, Game, Sprite, SpriteCollection};
use sdl2::keyboard::Scancode;
fn main() {
@ -21,7 +19,8 @@ fn main() {
coll.push(x);
}
}
play(String::from("output.mp3"), 120);
#[cfg(feature = "audio")]
cat_box::play("output.mp3", 120);
game.run(|ctx| {
i = (i + 1) % 255;
ctx.set_background_colour(i as u8, 64, 255);