Skip to content

Commit 4206ad5

Browse files
author
梶塚太智
committed
implemented command play-sound
1 parent 3bef705 commit 4206ad5

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/main.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
use rand::seq::SliceRandom;
22
use regex::Regex;
3+
use rodio::Source;
4+
use rodio::{OutputStream, Sink};
35
use std::collections::HashMap;
46
use std::env;
57
use std::fs::{self, File};
@@ -579,6 +581,39 @@ impl Executor {
579581
.collect::<Vec<Type>>(),
580582
)),
581583

584+
// Play sound from frequency
585+
"play-sound" => {
586+
fn play_sine_wave(frequency: f64, duration_secs: u64) {
587+
let sample_rate = 44100;
588+
589+
let num_samples = (duration_secs * sample_rate) as usize;
590+
let samples: Vec<f32> = (0..num_samples)
591+
.map(|t| {
592+
let t = t as f64 / sample_rate as f64;
593+
(t * frequency * 2.0 * std::f64::consts::PI).sin() as f32
594+
})
595+
.collect();
596+
597+
let (_stream, stream_handle) = OutputStream::try_default().unwrap();
598+
let sink = Sink::try_new(&stream_handle).unwrap();
599+
600+
for _ in samples {
601+
sink.append(
602+
rodio::source::SineWave::new(frequency as f32)
603+
.take_duration(Duration::from_secs(duration_secs)),
604+
);
605+
}
606+
607+
sink.play();
608+
std::thread::sleep(Duration::from_secs(duration_secs));
609+
}
610+
611+
let duration_secs = self.pop_stack().get_number() as u64;
612+
let frequency = self.pop_stack().get_number();
613+
614+
play_sine_wave(frequency, duration_secs);
615+
}
616+
582617
// Commands of control
583618

584619
// evaluate string as program

0 commit comments

Comments
 (0)