MCPcopy Index your code
hub / github.com/endbasic/endbasic / play_tone

Method play_tone

sdl/src/host.rs:364–405  ·  view source on GitHub ↗

Reproduces `tone` using SDL's audio queue.

(&mut self, tone: Tone)

Source from the content-addressed store, hash-verified

362
363 /// Reproduces `tone` using SDL's audio queue.
364 fn play_tone(&mut self, tone: Tone) -> io::Result<()> {
365 if tone.frequency_hz == 0 {
366 return Err(io::Error::new(
367 io::ErrorKind::InvalidInput,
368 "Tone frequency must be positive",
369 ));
370 }
371
372 let sample_count = (tone.duration.as_secs_f64() * f64::from(AUDIO_SAMPLE_RATE))
373 .round()
374 .clamp(0.0, usize::MAX as f64) as usize;
375 if sample_count == 0 {
376 return Ok(());
377 }
378
379 let samples = match tone.waveform {
380 Waveform::Square => {
381 let half_period = f64::from(AUDIO_SAMPLE_RATE) / f64::from(tone.frequency_hz) / 2.0;
382 let amplitude = i16::MAX / 4;
383 let mut samples = Vec::with_capacity(sample_count);
384 for i in 0..sample_count {
385 let sample = if (((i as f64) / half_period).floor() as u64).is_multiple_of(2) {
386 amplitude
387 } else {
388 -amplitude
389 };
390 samples.push(sample);
391 }
392 samples
393 }
394 };
395
396 let audio_device = self.get_audio_device()?;
397 audio_device.clear();
398 audio_device.queue_audio(&samples).map_err(string_error_to_io_error)?;
399 audio_device.resume();
400 while audio_device.size() > 0 {
401 thread::sleep(Duration::from_millis(1));
402 }
403 audio_device.pause();
404 Ok(())
405 }
406}
407
408impl RasterOps for Context {

Callers 1

runFunction · 0.45

Calls 4

clampMethod · 0.80
pushMethod · 0.80
get_audio_deviceMethod · 0.80
clearMethod · 0.45

Tested by

no test coverage detected