Day Vision

Reading Everyday,Extending Vision

iOS更新到12.1以后语音播报处理(Swift 含demo)

2023-02-28 04:00:39


去新公司接手的项目需要做语音播报,类似“支付宝到账100元”,上一个开发者只是做了前台播报,相对来说比较简单,接到推送后,在 func application(_ application: UIApplication, didReceive


去新公司接手的项目需要做语音播报,类似“支付宝到账100元”,上一个开发者只是做了前台播报,相对来说比较简单,接到推送后,在 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)方法中利用AVSpeechSynthesizer进行语音合成播报
  • 接手项目后新需求:后台程序杀死之后需要进行语音播报,但因为杀死程序接到通知必须用户相应才能做相应的处理,所以在appdelegate中肯定不能做,百度了一下 iOS10出的UNNotificationServiceExtension可以解决问题

集成 UNNotificationServiceExtension

第一步:引入 UNNotificationServiceExtension



第二步:点击next

第三步:填写Name后点击Finish

发现我们工程中多了 NotificationService.swift 文件,根据苹果官方文档,NotificationService.swift是为了丰富推送,给程序员修改推送内容的一次机会,相当于推送过来 我们会在NotificationService.swift中提前拿到通知,然后才会到推送弹框展示在用户眼前

iOS12.1之前语音播报

既然我们可以提前拿到通知,所以我们在NotificationService.swift中进行推送判断,看是否为语音播报,还是普通的推送

我们看到 NotificationService.swift中有个方法:
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void)
在这个方法中我们通过 request.content.userInfo 就可以拿到通知,由于是测试,我拿到 subtitle 对应内容,一般会在body里面,代码如下:

if let content = request.content.userInfo as? Dictionary<String,Any>,
                  let aps = content["aps"] as? Dictionary<String,Any>,
                  let alert = aps["alert"] as? Dictionary<String,Any>,
                  let str = alert["subtitle"] as? String{
}

这里加入我们拿到的str属性就是我们要播报的内容,例如str = "一卡通收款100元",接下来我们就行语音合成播报,代码如下:

let speaker = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: str)
utterance.rate = 0.5
et voice = AVSpeechSynthesisVoice(language: "zh-CN")
utterance.volume = 1
utterance.voice = voice
speaker.speak(utterance)

写到这里,试了一下,ok,完美解决,前台,后台,程序杀死语音播报完美,但是上线之后,悲催了,客户反映语音播报没声音,我立马测试了一下,没问题呀,然后拿同事的手机试了下,没声音,网上查资料发现在12.1以后NotificationService.swift中苹果不允许做语音合成播报,官方文档大致意思是:老子出NotificationService.swift是为了丰富通知,你却拿来做语音播报,老子不高兴了,以后不许用了。完蛋,既然在程序后台,杀死情况下语音播报,不让在这里写,没地去了。想了好多办法,都没解决,最后还是回到NotificationService.swift,既然你不让我语音合成,那我只能利用本地通知播放语音文件了。

iOS12.1以后语音播报

1.首先我们需要录制语音文件,你可以用百度,科大讯飞等,这里我用的百度语音,利用Pyhton脚本去生成文件,不想运行Python文件的直接去我代码里面去copy,Pyhton文件如下:
# -*- coding: utf-8 -*-
import os
from aip import AipSpeech



APP_ID = '15977485'
API_KEY = '9pQMw3sDbsjlc88PupjK63g8'
SECRET_KEY = '6pYLyuxadNvBTpRoRuAssOrbIxBwoK9G'

client = AipSpeech(APP_ID,API_KEY,SECRET_KEY)

def functionNum(num):
    if(num == 0):
        return "0"
    elif(num == 1):
        return "1"
    elif (num == 2):
        return "2"
    elif (num == 3):
        return "3"
    elif (num == 4):
        return "4"
    elif (num == 5):
        return "5"
    elif (num == 6):
        return "6"
    elif (num == 7):
        return "7"
    elif (num == 8):
        return "8"
    elif (num == 9):
        return "9"
    elif (num == 10):
        return "十"
    elif (num == 11):
        return "百"
    elif (num == 12):
        return "千"
    elif (num == 13):
        return "万"
    elif (num == 14):
        return "点"
    elif (num == 15):
        return "元"
    elif (num == 16):
        return "一卡通到账"
    elif (num == 17):
        return "一卡通收款一笔"

for i in range(0, 18):
    
    print(os.getcwd())
    filePath = '/Users/wang/Desktop/Sound/'
    
    text =  functionNum(i)
    result = client.synthesis(text,'zh',1,None)
    sound = text
    
    if not isinstance(result,dict):
        with open(sound+'.mp3','wb') as f:
            f.write(result)
    print(sound)

拿到语音文件后添加到工程中,注意一定是要勾选自己的工程和UNNotificationServiceExtension工程

开始在NotificationService.swift中写代码

  • 首先还是判断过来的通知是否为语音播报通知(和上面一样)
  • 判断当前的版本号,然后进行不同处理
if #available(iOS 12.1, *){//判断是否是12.1以上的系统
                    
                    bestAttemptContent.sound = nil
                    play_registerNotification(str: str)
                    
                }else{ //12.1以下的系统  直接执行语音合成播报
                    
                    bestAttemptContent.sound = UNNotificationSound.default
                    playVoiceWithContent(str: str)
                    contentHandler(bestAttemptContent)
                }
  • 如果是iOS12.1之前的版本,直接播报(和上面一样)

  • 如果是iOS12.1以后的版本

进行金额提取注册本地通知等

 // MARK: - 使用本地通知12.1以上系统
    func play_registerNotification(str:String){
        if !str.hasPrefix("一卡通到账"){ //通知内容不是金额播报类型
            bestAttemptContent?.sound = UNNotificationSound.default
            contentHandler!(bestAttemptContent!)
            return
        }
        
        if (str as NSString).length <= 10{ //长度问题
            bestAttemptContent?.sound = UNNotificationSound.default
            contentHandler!(bestAttemptContent!)
            return
        }
        
        let strCount = (str as NSString).substring(with: NSMakeRange(5, (str as NSString).length-5-1))
        
        print(strCount)
        
        if let countStr =  Float(strCount) {
            if countStr > 10000.0{
                //大于10000播放收款一笔
                bestAttemptContent?.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "一卡通收款一笔.mp3"))
                contentHandler!(bestAttemptContent!)
                return
            }else{ //小于10000的播放金额
                
                if let array = stringToArray("\(countStr)") {
                    print(array)
                     pushLocalNotification(array, 0)
                }
            }
            
        }else{
            bestAttemptContent?.sound = UNNotificationSound.default
            contentHandler!(bestAttemptContent!)
        }
    }

利用递归一个一个播放

 // MARK: - 使用本地通知12.1以上系统
    func play_registerNotification(str:String){
        if !str.hasPrefix("一卡通到账"){ //通知内容不是金额播报类型
            bestAttemptContent?.sound = UNNotificationSound.default
            contentHandler!(bestAttemptContent!)
            return
        }
        
        if (str as NSString).length <= 10{ //长度问题
            bestAttemptContent?.sound = UNNotificationSound.default
            contentHandler!(bestAttemptContent!)
            return
        }
        
        let strCount = (str as NSString).substring(with: NSMakeRange(5, (str as NSString).length-5-1))
        
        print(strCount)
        
        if let countStr =  Float(strCount) {
            if countStr > 10000.0{
                //大于10000播放收款一笔
                bestAttemptContent?.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "一卡通收款一笔.mp3"))
                contentHandler!(bestAttemptContent!)
                return
            }else{ //小于10000的播放金额
                
                if let array = stringToArray("\(countStr)") {
                    print(array)
                     pushLocalNotification(array, 0)
                }
            }
            
        }else{
            bestAttemptContent?.sound = UNNotificationSound.default
            contentHandler!(bestAttemptContent!)
        }
    }

我的拆分金额的方法,我们服务器语音播报的消息格式:一卡通到账100.32元

 // MARK: - 使用本地通知12.1以上系统
    func play_registerNotification(str:String){
        if !str.hasPrefix("一卡通到账"){ //通知内容不是金额播报类型
            bestAttemptContent?.sound = UNNotificationSound.default
            contentHandler!(bestAttemptContent!)
            return
        }
        
        if (str as NSString).length <= 10{ //长度问题
            bestAttemptContent?.sound = UNNotificationSound.default
            contentHandler!(bestAttemptContent!)
            return
        }
        
        let strCount = (str as NSString).substring(with: NSMakeRange(5, (str as NSString).length-5-1))
        
        print(strCount)
        
        if let countStr =  Float(strCount) {
            if countStr > 10000.0{
                //大于10000播放收款一笔
                bestAttemptContent?.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "一卡通收款一笔.mp3"))
                contentHandler!(bestAttemptContent!)
                return
            }else{ //小于10000的播放金额
                
                if let array = stringToArray("\(countStr)") {
                    print(array)
                     pushLocalNotification(array, 0)
                }
            }
            
        }else{
            bestAttemptContent?.sound = UNNotificationSound.default
            contentHandler!(bestAttemptContent!)
        }
    }

目前这种方案可以解决语音播报的问题,但也存在弊端,本地推送推送一个语音文件会震一次,所以可以引导用户去关闭震动。或者就是多录语音文件,例如123.06元,可以分为“一百二十三点” + “零六元”这种,算上前缀是1000多分语音文件,在拆分金额的时候方法根据实际情况改变,这样可以震三四次就可以解决语音播报的问题,但包会大一些。

注意:推送的字段一定要加 mutable-content:1 字段,否则程序推送不会走 UNNotificationServiceExtension.

再注意:支付宝的解决办法是voip(最完美的语音播报方案),但是如果你项目不支持通话功能,就不要用了,或者你可以试试,看能不能过审