记录iOS 语音播报封装
2020-09-18 本文已影响0人
舟_e9ce
需要实现 AVSpeechSynthesizerDelegate 代理
// 设置一段文字播报的次数
var speechNum : Int = 1
// 记录播报次数
var speechInit : Int = 0
private var avSpeaker : AVSpeechSynthesizer!
override init() {
super.init()
avSpeaker = AVSpeechSynthesizer()
avSpeaker.delegate = self
}
/// 开始播报
/// - Parameter content: 播报内容
func startSpeech(content : String) {
stopSpeech()
let tempContent = configSpeechContent(content: content)
let utterance = configUtterance(speechContent: tempContent)
avSpeaker.speak(utterance)
}
/// 停止播报
func stopSpeech() {
avSpeaker.stopSpeaking(at: .immediate)
}
/// 暂停播报
func pauseSpeech() {
avSpeaker.pauseSpeaking(at: .immediate)
}
/// 继续播报
func continueSpeech() {
avSpeaker.continueSpeaking()
}
/// 初始化播报的语音文字
/// - Parameter speechContent: 播报文字
/// - Returns: AVSpeechUtterance
func configUtterance(speechContent : String) -> AVSpeechUtterance {
let utterance = AVSpeechUtterance(string: speechContent)
// 设置语速
utterance.rate = 0.4
// 设置音高
utterance.pitchMultiplier = 1
// 设置音量
utterance.volume = 1
// 读一段话前停顿时间
utterance.preUtteranceDelay = 0
// 读完一段后的停顿时间
utterance.postUtteranceDelay = 0
// 设置声音 是 AVSpeechSynthesisVoice对象
let voice = AVSpeechSynthesisVoice(language: "zh-CN")
utterance.voice = voice
return utterance
}
/// 这里做处理主要是不想在读多位数字时读成几百,几十这种类型
/// 配置播报内容
/// - Parameter content: 播报数据源
/// - Returns: stirng
func configSpeechContent(content : String) -> String{
var speech = ""
for charStr in content.enumerated() {
speech = speech + " " + String(charStr.element)
}
return speech
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didPause utterance: AVSpeechUtterance) {
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
speechInit += 1
if speechInit == speechNum {
speechInit = 0
} else {
avSpeaker.speak(utterance)
}
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didContinue utterance: AVSpeechUtterance) {
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
}
图片.png