text 文本到语音的api ios

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 文本到语音的api ios相关的知识,希望对你有一定的参考价值。

import UIKit
import AVFoundation
import PlaygroundSupport

var str = "Turning to Right"

let synthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: str)
utterance.rate = 0.39 // more the rate more faster words will be uttered
utterance.voice = AVSpeechSynthesisVoice(language: "en-US") // fr-FR  en-US // hub of all codes:- https://gist.github.com/vitoziv/9108407

//for playground only
let playerViewController = AVPlayerViewController()
PlaygroundPage.current.liveView = playerViewController.view
//

synthesizer.speak(utterance)
// instructions to enable sound in background mode
1. tick the Audio, Airplay, and Picture in Picture functionality in background mode 
2. add the following line in viewWillAppear function
    override func viewWillAppear(_ animated: Bool) {
        try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
    }
3. enclose your code of synthesizer.speak()  to other in 
DispatchQueue.global().sync {
}

to run in global main thread.

ENJOY!!
    
  

以上是关于text 文本到语音的api ios的主要内容,如果未能解决你的问题,请参考以下文章