讓開不了口的 App 開口說話 !

利用 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 才能講英文以外的語言。

語言字串列表可參考以下連結。

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com