上代码
import UIKit
import AVFoundation
class ViewController: UIViewController {
fileprivate let synthesizer = AVSpeechSynthesizer()
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let utterance = AVSpeechUtterance(string: "语音转文字")
utterance.pitchMultiplier = 1
// 音量
utterance.volume = 1
// 语速
utterance.rate = 0.5
// 播放使用的语言, 这里用中文
let language = AVSpeechSynthesisVoice(language: "zh")
utterance.voice = language
synthesizer.speak(utterance)
synthesizer.delegate = self
/// 以下为常用操作
// let isSpeaking = synthesizer.isSpeaking // 正在播放
// let isPaused = synthesizer.isPaused // 已经暂停
// synthesizer.stopSpeaking(at: .immediate) // 立刻停止播放
// synthesizer.stopSpeaking(at: .word) // 播放完最后一个单词后停止播放
// synthesizer.pauseSpeaking(at: .immediate) // 立刻暂停播放
// synthesizer.pauseSpeaking(at: .word) // 播放完最后一个单词后暂停播放
// synthesizer.continueSpeaking() // 继续播放
}
}
extension ViewController: AVSpeechSynthesizerDelegate {
// 已经暂停
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didPause utterance: AVSpeechUtterance) {
}
// 已经开始
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
}
// 已经取消
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
}
// 已经播放完成
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
}
// 已经开始继续播放
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didContinue utterance: AVSpeechUtterance) {
}
// 即将开始播放
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeak marker: AVSpeechSynthesisMarker, utterance: AVSpeechUtterance) {
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
}
}
网友评论