Add support for volume and pitch.

This commit is contained in:
Nolan Darilek 2018-12-15 15:56:13 +00:00
parent bac4b7555f
commit e24ed9a3a3
3 changed files with 67 additions and 12 deletions

View File

@ -1,3 +1,5 @@
use std::u8;
use tts::TTS;
fn main() {
@ -6,10 +8,22 @@ fn main() {
tts.speak("Hello, world.", false);
let original_rate = tts.get_rate();
tts.speak(format!("Current rate: {}", original_rate), false);
tts.set_rate(std::u8::MAX);
tts.set_rate(u8::MAX);
tts.speak("This is very fast.", false);
tts.set_rate(0);
tts.speak("This is very slow.", false);
tts.set_rate(original_rate);
let original_pitch = tts.get_pitch();
tts.set_pitch(u8::MAX);
tts.speak("This is high-pitch.", false);
tts.set_pitch(0);
tts.speak("This is low pitch.", false);
tts.set_pitch(original_pitch);
let original_volume = tts.get_volume();
tts.set_volume(u8::MAX);
tts.speak("This is loud!", false);
tts.set_volume(0);
tts.speak("This is quiet.", false);
tts.set_volume(original_volume);
tts.speak("Goodbye.", false);
}

View File

@ -17,6 +17,18 @@ impl SpeechDispatcher {
}
}
fn u8_to_i32(v: u8) -> i32 {
let ratio: f32 = v as f32/u8::MAX as f32;
(ratio * 200. - 100.) as i32
}
fn i32_to_u8(v: i32) -> u8 {
let v = v as f32;
let ratio: f32 = (v + 100.) / 200.;
let v = ratio * u8::MAX as f32;
v as u8
}
impl Backend for SpeechDispatcher {
fn speak(&self, text: &str, interrupt: bool) {
trace!("speak({}, {})", text, interrupt);
@ -27,19 +39,26 @@ impl Backend for SpeechDispatcher {
}
fn get_rate(&self) -> u8 {
let rate = self.0.get_voice_rate() as f32;
trace!("get_voice_rate() = {}", rate);
let ratio: f32 = (rate + 100.) / 200.;
trace!("ratio = {}", ratio);
let rate = ratio * u8::MAX as f32;
trace!("rate = {}", rate);
rate as u8
i32_to_u8(self.0.get_voice_rate())
}
fn set_rate(&self, rate: u8) {
trace!("set_rate({})", rate);
let ratio: f32 = rate as f32/u8::MAX as f32;
let rate = ratio * 200. - 100.;
self.0.set_voice_rate(rate as i32);
self.0.set_voice_rate(u8_to_i32(rate));
}
fn get_pitch(&self) -> u8 {
i32_to_u8(self.0.get_voice_pitch())
}
fn set_pitch(&self, pitch: u8) {
self.0.set_voice_pitch(u8_to_i32(pitch));
}
fn get_volume(&self) -> u8 {
i32_to_u8(self.0.get_volume())
}
fn set_volume(&self, volume: u8) {
self.0.set_volume(u8_to_i32(volume));
}
}

View File

@ -11,6 +11,10 @@ trait Backend {
fn speak(&self, text: &str, interrupt: bool);
fn get_rate(&self) -> u8;
fn set_rate(&self, rate: u8);
fn get_pitch(&self) -> u8;
fn set_pitch(&self, pitch: u8);
fn get_volume(&self) -> u8;
fn set_volume(&self, volume: u8);
}
pub struct TTS(Box<Backend>);
@ -36,6 +40,24 @@ impl TTS {
self.0.set_rate(rate);
self
}
pub fn get_pitch(&self) -> u8 {
self.0.get_pitch()
}
pub fn set_pitch(&self, pitch: u8) -> &Self {
self.0.set_pitch(pitch);
self
}
pub fn get_volume(&self) -> u8 {
self.0.get_volume()
}
pub fn set_volume(&self, volume: u8) -> &Self {
self.0.set_volume(volume);
self
}
}
impl Default for TTS {