讓開不了口的 App 開口說話 !
Published in
Dec 26, 2017
利用 AVSpeechSynthesizer 講話
import UIKit
import AVFAudio
class ViewController: UIViewController {
let synthesizer = AVSpeechSynthesizer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func speak(_ sender: Any) {
let utterance = AVSpeechUtterance(string: "I love swift")
utterance.pitchMultiplier = 2
utterance.rate = 0.1
synthesizer.speak(utterance)
}
}
AVSpeechUtterance 是要講的話,AVSpeechSynthesizer 是發出聲音的合成器。呼叫 AVSpeechSynthesizer 的 speak function 講話,pitchMultiplier 控制講話的音調,範圍是 0.5 ~ 2,rate 控制講話的速度,範圍是 0 ~ 1。
說中文
import UIKit
import AVFAudio
class ViewController: UIViewController {
let synthesizer = AVSpeechSynthesizer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func speak(_ sender: Any) {
let utterance = AVSpeechUtterance(string: "我愛彼得潘")
utterance.voice = AVSpeechSynthesisVoice(language: "zh-TW")
synthesizer.speak(utterance)
}
}
AVSpeechSynthesisVoice 控制講話聲音的語言,設定 voice 才能講英文以外的語言。
語言字串列表可參考以下連結。