Skip to content

Commit

Permalink
Add fun text-to-speech example
Browse files Browse the repository at this point in the history
Here's to hoping it actually works, I don't have a new enough system to actually test it
  • Loading branch information
madsmtm committed Dec 22, 2021
1 parent 0da814d commit b0eddb4
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions objc2/examples/talk_to_me.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use objc2::ffi::NSUInteger;
use objc2::rc::{Id, Owned, Shared};
use objc2::runtime::Object;
use objc2::{class, msg_send};
use std::ffi::c_void;
use std::ptr::NonNull;

#[link(name = "AVFoundation", kind = "framework")]
extern "C" {}

// Only works on macOS >= 10.15 or iOS > 7.0
fn main() {
let text = "Hello from Rust!";

let string: *const Object = unsafe { msg_send![class!(NSString), alloc] };
let string = unsafe {
msg_send![
string,
initWithBytes: text.as_ptr() as *const c_void,
length: text.len(),
encoding: 4 as NSUInteger, // UTF8_ENCODING on macOS / iOS
]
};
let string: Id<Object, Shared> = unsafe { Id::new(NonNull::new(string).unwrap()) };

let synthesizer: *mut Object = unsafe { msg_send![class!(AVSpeechSynthesizer), new] };
let synthesizer: Id<Object, Owned> = unsafe { Id::new(NonNull::new(synthesizer).unwrap()) };

let utterance: *mut Object = unsafe { msg_send![class!(AVSpeechUtterance), alloc] };
let utterance: *mut Object = unsafe { msg_send![utterance, initWithString: &*string] };
let utterance: Id<Object, Owned> = unsafe { Id::new(NonNull::new(utterance).unwrap()) };

// let _: () = unsafe { msg_send![utterance, setVolume: 90.0f32 };
// let _: () = unsafe { msg_send![utterance, setRate: 0.50f32 };
// let _: () = unsafe { msg_send![utterance, setPitchMultiplier: 0.80f32 };

let _: () = unsafe { msg_send![synthesizer, speakUtterance: &*utterance] };
}

0 comments on commit b0eddb4

Please sign in to comment.