Skip to content

Add better support for loading SDL2 mixer sounds and music from memory #1483

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name = "sdl2"
description = "SDL2 bindings for Rust"
repository = "https://github.com/Rust-SDL2/rust-sdl2"
documentation = "https://docs.rs/sdl2"
version = "0.37.0"
version = "0.38.0"
license = "MIT"
authors = [ "Tony Aldridge <[email protected]>", "Cobrand <[email protected]>"]
keywords = ["SDL", "windowing", "graphics", "api", "engine"]
Expand All @@ -23,7 +23,7 @@ lazy_static = "1.4.0"

[dependencies.sdl2-sys]
path = "sdl2-sys"
version = "^0.37.0"
version = "^0.38.0"

[dependencies.c_vec]
# allow both 1.* and 2.0 versions
Expand Down
24 changes: 24 additions & 0 deletions examples/mixer-demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,30 @@ fn demo(music_file: &Path, sound_file: Option<&Path>) -> Result<(), String> {

timer.delay(5_000);
sdl2::mixer::Music::halt();

println!("playing sound from memory...");
let sound_as_bytes = include_bytes!("../assets/sine.wav");
let chunk = sdl2::mixer::Chunk::from_bytes(sound_as_bytes)?;
sdl2::mixer::Channel::all().play(&chunk, 0)?;
timer.delay(1_000);

println!("playing music from borrowed memory...");
let music_as_bytes = include_bytes!("../assets/sine.wav");

let mus = sdl2::mixer::Music::from_bytes(music_as_bytes)?;
mus.play(-1);
timer.delay(1_000);
sdl2::mixer::Music::halt();
timer.delay(0_500);

println!("playing music from owned memory...");

let mus = sdl2::mixer::Music::from_owned_bytes(music_as_bytes.clone().into())?;
mus.play(-1);
timer.delay(1_000);

sdl2::mixer::Music::halt();

timer.delay(1_000);

println!("quitting sdl");
Expand Down
2 changes: 1 addition & 1 deletion sdl2-sys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
name = "sdl2-sys"
description = "Raw SDL2 bindings for Rust, used internally rust-sdl2"
repository = "https://github.com/rust-sdl2/rust-sdl2"
version = "0.37.0"
version = "0.38.0"
authors = ["Tony Aldridge <[email protected]>", "Cobrand <[email protected]>"]
keywords = ["SDL", "windowing", "graphics", "ffi"]
categories = ["rendering","external-ffi-bindings","game-engines","multimedia"]
Expand Down
68 changes: 67 additions & 1 deletion src/sdl2/mixer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,17 @@ impl Drop for Chunk {
}

impl Chunk {
/// Load a sample from memory directly.
///
/// This works the same way as [Chunk::from_file] except with bytes instead of a file path.
/// If you have read your sound files (.wav, .ogg, etc...) from
/// disk to memory as bytes you can use this function
/// to create [Chunk]s from their bytes.
pub fn from_bytes(path: &[u8]) -> Result<Chunk, String> {
let b = RWops::from_bytes(path)?;
b.load_wav()
}

/// Load file for use as a sample.
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Chunk, String> {
let raw = unsafe { mixer::Mix_LoadWAV_RW(RWops::from_file(path, "rb")?.raw(), 0) };
Expand Down Expand Up @@ -363,6 +374,7 @@ impl<'a> LoaderRWops<'a> for RWops<'a> {
Ok(Music {
raw,
owned: true,
owned_data: None,
_marker: PhantomData,
})
}
Expand Down Expand Up @@ -799,6 +811,7 @@ extern "C" fn c_music_finished_hook() {
pub struct Music<'a> {
pub raw: *mut mixer::Mix_Music,
pub owned: bool,
pub owned_data: Option<Box<[u8]>>,
_marker: PhantomData<&'a ()>,
}

Expand All @@ -819,6 +832,8 @@ impl<'a> fmt::Debug for Music<'a> {

impl<'a> Music<'a> {
/// Load music file to use.
///
/// The music is streamed directly from the file when played.
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Music<'static>, String> {
let raw = unsafe {
let c_path = CString::new(path.as_ref().to_str().unwrap()).unwrap();
Expand All @@ -830,6 +845,31 @@ impl<'a> Music<'a> {
Ok(Music {
raw,
owned: true,
owned_data: None,
_marker: PhantomData,
})
}
}

/// Load music from a byte buffer.
///
/// The bytes' lifetime is tied to the returned [Music] instance,
/// so consider using [Music::from_owned_bytes] if that is an issue.
#[doc(alias = "SDL_RWFromConstMem")]
pub fn from_bytes(buf: &'a [u8]) -> Result<Music<'a>, String> {
let rw =
unsafe { sys::SDL_RWFromConstMem(buf.as_ptr() as *const c_void, buf.len() as c_int) };
if rw.is_null() {
return Err(get_error());
}
let raw = unsafe { mixer::Mix_LoadMUS_RW(rw, 0) };
if raw.is_null() {
Err(get_error())
} else {
Ok(Music {
raw,
owned: true,
owned_data: None,
_marker: PhantomData,
})
}
Expand All @@ -840,18 +880,44 @@ impl<'a> Music<'a> {
pub fn from_static_bytes(buf: &'static [u8]) -> Result<Music<'static>, String> {
let rw =
unsafe { sys::SDL_RWFromConstMem(buf.as_ptr() as *const c_void, buf.len() as c_int) };

if rw.is_null() {
return Err(get_error());
}
let raw = unsafe { mixer::Mix_LoadMUS_RW(rw, 0) };
if raw.is_null() {
Err(get_error())
} else {
Ok(Music {
raw,
owned: true,
owned_data: None,
_marker: PhantomData,
})
}
}

/// Load music from an owned byte buffer.
///
/// The returned [Music] instance takes ownership of the given buffer
/// and drops it along with itself.
///
/// Loading the whole music data to memory can be wasteful if the music can be streamed directly from
/// a file instead. Consider using [Music::from_file] when possible.
#[doc(alias = "SDL_RWFromConstMem")]
pub fn from_owned_bytes(mut buf: Box<[u8]>) -> Result<Music<'static>, String> {
let rw =
unsafe { sys::SDL_RWFromConstMem(buf.as_ptr() as *const c_void, buf.len() as c_int) };
if rw.is_null() {
return Err(get_error());
}
let raw = unsafe { mixer::Mix_LoadMUS_RW(rw, 0) };
if raw.is_null() {
Err(get_error())
} else {
Ok(Music {
raw,
owned: true,
owned_data: Some(buf),
_marker: PhantomData,
})
}
Expand Down
Loading