
Xcode配置
- 如果需要后臺(tái)播報(bào)語(yǔ)音,需要到Target->Capabilities選中Background Modes 的 Audio...選項(xiàng)。

若不勾選此項(xiàng),程序在后臺(tái)運(yùn)行的時(shí)候調(diào)用語(yǔ)音播報(bào)會(huì)報(bào)出codeCannotStartPlaying錯(cuò)誤。

管理類(lèi)文件
import AVFoundation
class SpeechUtteranceManager: NSObject {
/// 單例管理語(yǔ)音播報(bào) 比較適用于多種類(lèi)型語(yǔ)音播報(bào)管理
public static let shared = SpeechUtteranceManager()
var synthesizer = AVSpeechSynthesizer()
var speechUtterance: AVSpeechUtterance?
var voiceType = AVSpeechSynthesisVoice(language: Locale.current.languageCode)
private override init() {
super.init()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)
} catch {
print(error.localizedDescription)
}
synthesizer.delegate = self
}
/// 自定義語(yǔ)音播報(bào)方法
/// 此處只舉例播報(bào)一個(gè)String的情況
func speechWeather(with weather: String) {
if let _ = speechUtterance {
synthesizer.stopSpeaking(at: .immediate)
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print(error.localizedDescription)
}
speechUtterance = AVSpeechUtterance(string: weather)
speechUtterance?.voice = voiceType
speechUtterance?.rate = 0.5
synthesizer.speak(speechUtterance!)
}
}
extension SpeechUtteranceManager: AVSpeechSynthesizerDelegate {
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
do {
try AVAudioSession.sharedInstance().setActive(false, with: .notifyOthersOnDeactivation)
} catch {
print(error.localizedDescription)
}
speechUtterance = nil
}
}
使用
/// 例如播報(bào)天氣
/// 若要兼容語(yǔ)言國(guó)際化
/// NSLocalizedString 搭配 Locale.current.languageCode 食用效果更佳
SpeechUtteranceManager.shared.speechWeather(with: NSLocalizedString("The Rainy Day", comment: ""))
關(guān)鍵代碼
setCategory
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)
} catch {
print(error.localizedDescription)
}
- AVAudioSessionCategoryPlayback:后臺(tái)播報(bào)
- .duckOthers:混合通道,語(yǔ)音播報(bào)時(shí)其他軟件聲音變?。ㄒ魳?lè))
若不設(shè)置混合通道,在后臺(tái)播報(bào)時(shí)會(huì)報(bào)codeCannotInterruptOthers錯(cuò)誤

setActive
將 AVAudioSession 置為活動(dòng)狀態(tài)
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print(error.localizedDescription)
}
記得在結(jié)束調(diào)用時(shí)將活動(dòng)狀態(tài)置為false
do {
try AVAudioSession.sharedInstance().setActive(false)
} catch {
print(error.localizedDescription)
}