ios12.1以后系统不在支持语音播报
废话不多说直接来硬货
oc版本参考这个https://www.jianshu.com/p/e075125603ee
本文意识参考这个作者弄出来的 我用的swift 这里讲一下swift的集成
首先notificationservice要集成(这里不多说了)
if #available(iOS 12.0, *) {
if bestAttemptContent!.body.contains("收到消费者"){
let str = self.getIntFromString(str: bestAttemptContent!.body)
var array = [String]()
array.append("tts_success")
for i in 0..<str.count{
let ns=(str as NSString).substring(with: NSMakeRange(i, 1))
if ns == "."{
array.append("tts_dot")
}else{
array.append("tts_\(ns)")
}
}
array.append("tts_yuan")
self.pushRed(arr: array)
}
} else {
readContent(str: bestAttemptContent!.body)
}
这里区分一下 在12或者以上就用新的方法
新的方法是获取推送内容 然后获取内容的数字 然后循环获取获取数字中的每个字符
以便于后面播报
func pushRed(arr:[String]){
for i in arr{
let semaphore = DispatchSemaphore.init(value: 0)
self.ppp(idStr: i) { (data) in
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.7, execute: {
semaphore.signal()
})
}
semaphore.wait()
}
self.contentHandler!(self.bestAttemptContent!)
}
//MARK:本地推送播报
func ppp(idStr:String,finishedCallback : @escaping (_ json : AnyObject) -> ()){
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent.init()
content.title = ""
content.body = ""
if #available(iOS 12.0, *) {
content.sound = UNNotificationSound.criticalSoundNamed("\(idStr).mp3")
} else {
// Fallback on earlier versions
}
//content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.01, repeats: false)
let request = UNNotificationRequest.init(identifier: idStr, content: content, trigger: trigger)
center.add(request) { (error) in
finishedCallback("123" as AnyObject)
}
}
/// 从字符串中提取数字
func getIntFromString(str:String) -> String {
let scanner = Scanner(string: str)
scanner.scanUpToCharacters(from: CharacterSet.decimalDigits, into: nil)
var number:Float = 0
//scanner.scanInt(&number)
scanner.scanFloat(&number)
print(number)
return String(number)
}
这里三个方法 最后一个方法是获取字符串中的数字
倒数第二个是本地无内容推送播放mp3格式的
倒数第三个方法就是调用
以上代码全部写在notificationservice里面就可以了
语音播报搞定!
网友评论