涉及到音视频的知识那肯定离不开 AVFoundation 框架啦。
所以实现的第一步那就是 import AVFoundation
实现语音读取文字,需要两个至关重要的类: 1.AVSpeechSynthesizer 语音合成器类 2.AVSpeechUtterance 语音表达设置类 这两个类都很简单,API 中的东西都很少。接下来实现一个小的功能,就是读取 textView 里输入的文字。 直接看实现的代码吧。
let syntesizer = AVSpeechSynthesizer()
var utterance = AVSpeechUtterance()
复制代码
播放
@IBAction func play(_ sender: UIButton) {
// 获取 textView 输入的文字
let string = textView.text
// 设置将要语音的文字
utterance = AVSpeechUtterance(string: string!)
// 语音的速度
utterance.rate = 0.1
// 开始朗读
syntesizer.speak(utterance)
}
复制代码
暂停
@IBAction func pause(_ sender: UIButton) {
// 暂停朗读
syntesizer.pauseSpeaking(at: .immediate)
}
复制代码
继续
@IBAction func continuePlay(_ sender: UIButton) {
// 继续朗读
syntesizer.continueSpeaking()
}
复制代码
停止
@IBAction func stopPlay(_ sender: UIButton) {
// 停止之后,继续是无法继续播放的,因为不是暂停
syntesizer.stopSpeaking(at: .immediate)
}
复制代码
代理
AVSpeechSynthesizer类有一个协议,实现他们可以做一些相应的处理。
extension ViewController: AVSpeechSynthesizerDelegate {
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
print("开始")
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
print("完成")
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didPause utterance: AVSpeechUtterance) {
print("暂停")
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didContinue utterance: AVSpeechUtterance) {
print("继续")
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
print("停止")
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
print("阅读过程中")
}
}
复制代码