|
| 1 | +use std::ffi::CString; |
| 2 | +use wxdragon_sys as ffi; |
| 3 | + |
| 4 | +widget_style_enum!( |
| 5 | + name: SoundFlags, |
| 6 | + doc: "Flags for playing sounds.", |
| 7 | + variants: { |
| 8 | + Sync: ffi::wxd_SoundFlags_WXD_SOUND_SYNC as i64, "Play sound synchronously (waits for sound to finish).", |
| 9 | + Async: ffi::wxd_SoundFlags_WXD_SOUND_ASYNC as i64, "Play sound asynchronously (doesn't wait).", |
| 10 | + Loop: ffi::wxd_SoundFlags_WXD_SOUND_LOOP as i64, "Loop the sound until stopped." |
| 11 | + }, |
| 12 | + default_variant: Async |
| 13 | +); |
| 14 | + |
| 15 | +/// Represents a sound that can be played. |
| 16 | +/// |
| 17 | +/// wxSound is typically limited to WAV files. |
| 18 | +pub struct Sound { |
| 19 | + ptr: *mut ffi::wxd_Sound_t, |
| 20 | +} |
| 21 | + |
| 22 | +impl Sound { |
| 23 | + /// Creates a new sound from a file. |
| 24 | + /// |
| 25 | + /// # Arguments |
| 26 | + /// * `file_name` - Path to the sound file (usually .wav). |
| 27 | + /// * `is_resource` - If true, file_name is a resource name (Windows only). |
| 28 | + pub fn new(file_name: &str, is_resource: bool) -> Self { |
| 29 | + let c_file = CString::new(file_name).expect("CString::new failed"); |
| 30 | + let ptr = unsafe { ffi::wxd_Sound_Create(c_file.as_ptr(), is_resource) }; |
| 31 | + Self { ptr } |
| 32 | + } |
| 33 | + |
| 34 | + /// Returns true if the sound was created successfully. |
| 35 | + pub fn is_ok(&self) -> bool { |
| 36 | + if self.ptr.is_null() { |
| 37 | + return false; |
| 38 | + } |
| 39 | + unsafe { ffi::wxd_Sound_IsOk(self.ptr) } |
| 40 | + } |
| 41 | + |
| 42 | + /// Plays the sound with given flags. |
| 43 | + pub fn play(&self, flags: SoundFlags) -> bool { |
| 44 | + if self.ptr.is_null() { |
| 45 | + return false; |
| 46 | + } |
| 47 | + unsafe { ffi::wxd_Sound_Play(self.ptr, flags.bits() as u32) } |
| 48 | + } |
| 49 | + |
| 50 | + /// Plays a sound file directly without creating a Sound object. |
| 51 | + pub fn play_file(file_name: &str, flags: SoundFlags) -> bool { |
| 52 | + let c_file = match CString::new(file_name) { |
| 53 | + Ok(s) => s, |
| 54 | + Err(_) => return false, |
| 55 | + }; |
| 56 | + unsafe { ffi::wxd_Sound_PlayFile(c_file.as_ptr(), flags.bits() as u32) } |
| 57 | + } |
| 58 | + |
| 59 | + /// Stops any currently playing sound. |
| 60 | + pub fn stop() { |
| 61 | + unsafe { ffi::wxd_Sound_Stop() } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +impl Drop for Sound { |
| 66 | + fn drop(&mut self) { |
| 67 | + if !self.ptr.is_null() { |
| 68 | + unsafe { ffi::wxd_Sound_Destroy(self.ptr) }; |
| 69 | + } |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +unsafe impl Send for Sound {} |
0 commit comments