Swift 字符串轉(zhuǎn)語(yǔ)音播放

上代碼

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: "語(yǔ)音轉(zhuǎn)文字")
        utterance.pitchMultiplier = 1
        // 音量
        utterance.volume = 1
        // 語(yǔ)速
        utterance.rate = 0.5
        
        // 播放使用的語(yǔ)言, 這里用中文
        let language = AVSpeechSynthesisVoice(language: "zh")
        utterance.voice = language
        
        synthesizer.speak(utterance)
        synthesizer.delegate = self
        
        /// 以下為常用操作
//        let isSpeaking = synthesizer.isSpeaking // 正在播放
//        let isPaused = synthesizer.isPaused // 已經(jīng)暫停
//        synthesizer.stopSpeaking(at: .immediate) // 立刻停止播放
//        synthesizer.stopSpeaking(at: .word) // 播放完最后一個(gè)單詞后停止播放
//        synthesizer.pauseSpeaking(at: .immediate) // 立刻暫停播放
//        synthesizer.pauseSpeaking(at: .word) // 播放完最后一個(gè)單詞后暫停播放
//        synthesizer.continueSpeaking() // 繼續(xù)播放
    }
}

extension ViewController: AVSpeechSynthesizerDelegate {
    // 已經(jīng)暫停
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didPause utterance: AVSpeechUtterance) {
        
    }
    
    // 已經(jīng)開(kāi)始
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
        
    }
    
    // 已經(jīng)取消
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
    
    }
    
    // 已經(jīng)播放完成
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
        
    }
    // 已經(jīng)開(kāi)始繼續(xù)播放
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didContinue utterance: AVSpeechUtterance) {
        
    }
    
    // 即將開(kāi)始播放
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeak marker: AVSpeechSynthesisMarker, utterance: AVSpeechUtterance) {
        
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
        
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容