From af7b4f77bb88f956fdcebf7d2972b3c8acf3bf6b Mon Sep 17 00:00:00 2001 From: Breval Ferrari Date: Mon, 17 Mar 2025 00:49:32 -0400 Subject: [PATCH] add open function for audio --- bingus/src/lib.rs | 8 ++++++-- bingus/src/snd.rs | 3 ++- bingus/src/snd/simphonia.rs | 34 +++++++++++++++++++++++++++++++++- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/bingus/src/lib.rs b/bingus/src/lib.rs index 4ce202a..6edd9f8 100644 --- a/bingus/src/lib.rs +++ b/bingus/src/lib.rs @@ -12,6 +12,8 @@ mod dynamic { path::Path, }; + use crate::snd::{self, Audio}; + use super::{ img::{self, DynamicImage}, Bytes, @@ -26,7 +28,7 @@ mod dynamic { pub enum DynamicBendable { Image(DynamicImage), Binary(Bytes), - Sound, + Sound(Audio), Text, } @@ -36,6 +38,8 @@ mod dynamic { Io(#[from] io::Error), #[error("{0:?}")] Image(#[from] img::ImageError), + #[error("{0:?}")] + Audio(#[from] snd::AudioOpenError), } pub fn open>(path: P) -> Result, OpenError> { @@ -50,7 +54,7 @@ mod dynamic { File::open(path)?.read_to_end(&mut buf)?; buf })), - Audio => todo!(), + Audio => Some(DynamicBendable::Sound(crate::snd::Audio::open(path)?)), Book => todo!(), Doc => todo!(), Font => todo!(), diff --git a/bingus/src/snd.rs b/bingus/src/snd.rs index 0b7b8fc..1de55b0 100644 --- a/bingus/src/snd.rs +++ b/bingus/src/snd.rs @@ -1,4 +1,5 @@ pub use symphonia::core::sample::Sample; mod raw; -pub use raw::RawSamples; +pub use raw::*; mod simphonia; +pub use simphonia::*; diff --git a/bingus/src/snd/simphonia.rs b/bingus/src/snd/simphonia.rs index 9be1ce4..442c727 100644 --- a/bingus/src/snd/simphonia.rs +++ b/bingus/src/snd/simphonia.rs @@ -1,4 +1,8 @@ -use std::io::{self, Read}; +use std::{ + fs::File, + io::{self, Read}, + path::Path, +}; use derive_new::new; use symphonia::{ @@ -14,6 +18,7 @@ use symphonia::{ }, default, }; +use thiserror::Error; use crate::{IntoDataBytes, TryFromDataBytes}; @@ -28,6 +33,33 @@ pub struct Audio { decoder: Box, } +#[derive(Debug, Error)] +pub enum AudioOpenError { + #[error("IO error: {0}")] + Io(#[from] io::Error), + #[error("symphonia can't open this file: {0}")] + Symphonia(#[from] symphonia::core::errors::Error), +} + +impl Audio { + pub fn open>(path: P) -> Result { + let registry = default::get_codecs(); + let probe = default::get_probe(); + let mediasource = File::open(path.as_ref())?; + let mss = MediaSourceStream::new(Box::new(mediasource), Default::default()); + let reader = probe + .format( + &Default::default(), + mss, + &Default::default(), + &Default::default(), + )? + .format; + let decoder = registry.make(&Default::default(), &Default::default())?; + Ok(Audio::new(reader, decoder)) + } +} + impl TryFromDataBytes for Audio { type Error = Error; type Format = Hint;