Skip to content

Instantly share code, notes, and snippets.

View myrickchow32's full-sized avatar

Myrick Chow myrickchow32

  • RedSo
  • Hong Kong
View GitHub Profile
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationDidEnterBackground(_ application: UIApplication) {
// AVSpeechSynthesizer will be automatically stopped with a smooth volume reduction
// The parameter of stopping the speech is AVSpeechBoundary.immediate
print("applicationDidEnterBackground")
}
func applicationDidBecomeActive(_ application: UIApplication) {
// AVSpeechSynthesizer will be automatically resumed
print("applicationDidBecomeActive")
var avSpeechSynthesizer: AVSpeechSynthesizer!
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
avSpeechSynthesizer.stopSpeaking(at: .immediate)
}
class AVFoundataionDemoViewController: BaseViewController {
let avSpeechSynthesizer = AVSpeechSynthesizer()
override func viewDidLoad() {
super.viewDidLoad()
avSpeechSynthesizer.delegate = self
}
}
extension AVFoundataionDemoViewController: AVSpeechSynthesizerDelegate {
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
import AVFoundation
let avSpeechSynthesizer = AVSpeechSynthesizer()
avSpeechSynthesizer.delegate = self
// Session 1 --- AVSpeechUtterance: 7 Parameters of synthesized speech
let utterance = AVSpeechUtterance(string: "Hello world")
utterance.voice = ...
utterance.rate = ...
utterance.pitchMultiplier = ...
/*
Pitch multiplier range: 0.5 to 2.0
Default value: 1.0
*/
let utterance = AVSpeechUtterance(string: "Hello world")
utterance.pitchMultiplier = 1.0
/*
Range: 0.0 - 1.0
AVSpeechUtteranceMinimumSpeechRate: 0.0
AVSpeechUtteranceMaximumSpeechRate: 1.0
AVSpeechUtteranceDefaultSpeechRate: 0.5
*/
let utterance = AVSpeechUtterance(string: "Hello world")
utterance.rate = 0.5
let utterance = AVSpeechUtterance(string: "Hello world")
utterance.volume = 0.5 // Range: 0.0 - 1.0 ; A relative volume to the device volume
let utterance = AVSpeechUtterance(string: "Hello world")
// Method 1: Directly by identifier
utterance.voice = AVSpeechSynthesisVoice(identifier: "com.apple.ttsbundle.Karen-compact")
// Method 2: By langauge code
utterance.voice = AVSpeechSynthesisVoice(language: "en-AU")
let speechVoices = AVSpeechSynthesisVoice.speechVoices()
speechVoices.forEach { (voice) in
print("**********************************")
print("Voice identifier: \(voice.identifier)")
print("Voice language: \(voice.language)")
print("Voice name: \(voice.name)")
print("Voice quality: \(voice.quality.rawValue)") // Compact: 1 ; Enhanced: 2
}
/*
let utterance = AVSpeechUtterance(string: "Hello world")