Files
OrderScheduling/Pods/DDAudioPlayerKit_Private/DDAudioPlayerKit_Private/Classes/DDSpeechSynthesizer.swift
DDIsFriend 7fda9d2650 update
2023-09-06 15:17:24 +08:00

94 lines
3.1 KiB
Swift

//
// DDSpeechSynthesizer.swift
// DDAudioPlayerKit_Private
//
// Created by on 2023/9/5.
//
import Foundation
import AVFoundation
public let DDSS = DDSpeechSynthesizer.default
open class DDSpeechSynthesizer {
public static let `default` = DDSpeechSynthesizer()
private var items : [DDSpeechSynthesizerItem] = []
public func play(text:String,name:String,numberOfLoops:Int = 1,timeInterval:TimeInterval = 0,eachLoopCompletionBlock: (() -> Void)? = nil, endCompletionBlock: (() -> Void)? = nil) {
let item = DDSpeechSynthesizerItem(name: name)
items.append(item)
item.play(text: text,numberOfLoops:numberOfLoops,timeInterval:timeInterval,eachLoopCompletionBlock:eachLoopCompletionBlock,endCompletionBlock:endCompletionBlock)
}
public func stop(name:String) {
if items.contains(where: { item in
item.name == name
}) == true {
if let index = items.firstIndex(where: { item in
item.name == name
}) {
let item = items[index]
item.stop()
items.remove(at: index)
}
}
}
}
class DDSpeechSynthesizerItem: NSObject, AVSpeechSynthesizerDelegate {
private var synthesizer : AVSpeechSynthesizer?
private var utterance : AVSpeechUtterance?
public var name : String
private var numberOfLoops : Int = 0
private var timeInterval : TimeInterval = 0
private var eachLoopCompletionBlock : (() -> Void)?
private var endCompletionBlock : (() -> Void)?
init(name:String) {
self.name = name
}
func play(text:String,numberOfLoops:Int,timeInterval:TimeInterval,eachLoopCompletionBlock: (() -> Void)?, endCompletionBlock: (() -> Void)?) {
self.numberOfLoops = numberOfLoops
self.timeInterval = timeInterval
self.eachLoopCompletionBlock = eachLoopCompletionBlock
self.endCompletionBlock = endCompletionBlock
synthesizer = AVSpeechSynthesizer()
synthesizer?.delegate = self
utterance = AVSpeechUtterance(string: text)
utterance?.voice = AVSpeechSynthesisVoice(language: "zh-Hans")
utterance?.rate = AVSpeechUtteranceDefaultSpeechRate
if let utterance {
synthesizer?.speak(utterance)
}
}
public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
if eachLoopCompletionBlock != nil {
eachLoopCompletionBlock!()
}
numberOfLoops-=1
if numberOfLoops == 0 {
if endCompletionBlock != nil {
endCompletionBlock!()
}
}else{
DispatchQueue.global().asyncAfter(deadline: .now() + timeInterval, execute: {[weak self] in
if let utterance = self?.utterance {
self?.synthesizer?.speak(utterance)
}
})
}
}
func stop() {
synthesizer?.stopSpeaking(at: .immediate)
synthesizer?.delegate = nil
synthesizer = nil
utterance = nil
}
}