Skip to content

Commit fd9813a

Browse files
committed
Provide AudioFormatNum.SILENCE constant
With the current callback function signatures it'll be both easier to use than AudioSpec.silence and it's correct in all cases. Closes issue #934.
1 parent 72d199e commit fd9813a

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/sdl2/audio.rs

+32
Original file line numberDiff line numberDiff line change
@@ -346,31 +346,59 @@ where Self::Channel: AudioFormatNum + 'static
346346
/// All format types are returned as native-endian.
347347
pub trait AudioFormatNum {
348348
fn audio_format() -> AudioFormat;
349+
350+
/// The appropriately typed silence value for the audio format used.
351+
///
352+
/// # Examples
353+
///
354+
/// ```
355+
/// // The AudioFormatNum trait has to be imported for the Channel::SILENCE part to work.
356+
/// use sdl2::audio::{AudioCallback, AudioFormatNum};
357+
///
358+
/// struct Silence;
359+
///
360+
/// impl AudioCallback for Silence {
361+
/// type Channel = u16;
362+
///
363+
/// fn callback(&mut self, out: &mut [u16]) {
364+
/// for dst in out.iter_mut() {
365+
/// *dst = Self::Channel::SILENCE;
366+
/// }
367+
/// }
368+
/// }
369+
/// ```
370+
const SILENCE: Self;
349371
}
350372

351373
/// `AUDIO_S8`
352374
impl AudioFormatNum for i8 {
353375
fn audio_format() -> AudioFormat { AudioFormat::S8 }
376+
const SILENCE: i8 = 0;
354377
}
355378
/// `AUDIO_U8`
356379
impl AudioFormatNum for u8 {
357380
fn audio_format() -> AudioFormat { AudioFormat::U8 }
381+
const SILENCE: u8 = 0x80;
358382
}
359383
/// `AUDIO_S16`
360384
impl AudioFormatNum for i16 {
361385
fn audio_format() -> AudioFormat { AudioFormat::s16_sys() }
386+
const SILENCE: i16 = 0;
362387
}
363388
/// `AUDIO_U16`
364389
impl AudioFormatNum for u16 {
365390
fn audio_format() -> AudioFormat { AudioFormat::u16_sys() }
391+
const SILENCE: u16 = 0x8000;
366392
}
367393
/// `AUDIO_S32`
368394
impl AudioFormatNum for i32 {
369395
fn audio_format() -> AudioFormat { AudioFormat::s32_sys() }
396+
const SILENCE: i32 = 0;
370397
}
371398
/// `AUDIO_F32`
372399
impl AudioFormatNum for f32 {
373400
fn audio_format() -> AudioFormat { AudioFormat::f32_sys() }
401+
const SILENCE: f32 = 0.0;
374402
}
375403

376404
extern "C" fn audio_callback_marshall<CB: AudioCallback>
@@ -473,6 +501,10 @@ pub struct AudioSpec {
473501
pub freq: i32,
474502
pub format: AudioFormat,
475503
pub channels: u8,
504+
/// The silence value calculated by SDL2. Note that it's inconvenient to use if your channel
505+
/// type is not u8 and [incorrect in case of u16](https://bugzilla.libsdl.org/show_bug.cgi?id=4805).
506+
/// You're likely to find [the `AudioFormatNum.SILENCE` associated constant](
507+
/// trait.AudioFormatNum.html#associatedconstant.SILENCE) more useful.
476508
pub silence: u8,
477509
pub samples: u16,
478510
pub size: u32

0 commit comments

Comments
 (0)