先添加UNNotificationServiceExtension家妆。File - new - targrt - UNNotificationServiceExtension
項(xiàng)目和UNNotificationServiceExtension钠龙,都要添加appGroups蝗拿,GroupIdentifier要一致,一般是"group.自己項(xiàng)目的BundleIdentifier"凝化,不一致會(huì)有問(wèn)題稍坯。
添加appGroups的原因是:共享一個(gè)group后,可以合成播報(bào)語(yǔ)音搓劫,然后存到group中遵班,之后在UNNotificationServiceExtension中可以讀取到合成后的語(yǔ)音文件祭埂。
UNNotificationServiceExtension的Minimum Deployment最低版本號(hào)要改一下,默認(rèn)是最高iOS系統(tǒng)版本。會(huì)出現(xiàn)低版本真機(jī)調(diào)試不可用的情況
網(wǎng)上的實(shí)現(xiàn)方式有3種旋奢,我用的是第一種炊豪。
關(guān)于音頻的拼接湃缎,如果用Data數(shù)據(jù)流的方式拼接岁忘,會(huì)出現(xiàn)只有第一段音頻聲音的問(wèn)題,所有還是要用AVAssetExportSession來(lái)拼接深员。
1種是修改系統(tǒng)的通知聲音负蠕,可以實(shí)現(xiàn)效果,但是因?yàn)橐袅坎荒苷{(diào)節(jié)倦畅,聲音太小遮糖。如果對(duì)音量沒(méi)有要求的,可以用這個(gè)方案叠赐,而且體驗(yàn)更好欲账。
//自定義通知聲音
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
let keyS = bestAttemptContent?.userInfo["key"] as? String
if keyS == "sound" {
let valueS = bestAttemptContent?.userInfo["value"] as? String//金額
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "zh-CN")
formatter.allowsFloats = true
let strF: CGFloat = formatter.number(from: valueS ?? "0") as? CGFloat ?? 0.0
formatter.numberStyle = . spellOut
let resultS: String = formatter.string(from: NSNumber (value: strF)) ?? ""
let resultSA: Array<String> = resultS.map { String($0) }
var finalA: Array<String> = ["錢(qián)響", "哥小兔到賬"]
finalA.append(contentsOf: resultSA)
finalA.append("元")
mergeAVAsset(with: finalA) { (name,path) in
if let bestAttemptContent = self.bestAttemptContent {
let temp3 = UNNotificationSoundName(rawValue: name ?? "")
let temp4 = UNNotificationSound.init(named: temp3)
bestAttemptContent.sound = temp4
contentHandler(bestAttemptContent)
}
}
} else {
if let bestAttemptContent = self.bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}
第2種是:AVAudioPlayer播放語(yǔ)音,瑕疵點(diǎn)就是芭概,推送橫幅要在語(yǔ)音播報(bào)結(jié)束后出現(xiàn)赛不,不然就會(huì)和AVAudioPlayer語(yǔ)音播報(bào)沖突。(功能實(shí)現(xiàn)了罢洲,但是打包上傳有問(wèn)題踢故,這個(gè)當(dāng)打包上傳到Appstore上就會(huì)出現(xiàn)錯(cuò)誤了,提示說(shuō)UNNotificationServiceExtension中的UIBackgroundModes的Audio這個(gè)字段是非法的惹苗,如果是企業(yè)分發(fā)模式可以添加殿较。要上架審核的話,是無(wú)法添加的)所以這個(gè)方法只適合企業(yè)分發(fā)用鸽粉,上架的話暫時(shí)還是用上面的第1方法斜脂。
UNNotificationServiceExtension 要添加一下權(quán)限抓艳,否則AVAudioPlayer不能在UNNotificationServiceExtension中播放
import UserNotifications
import MediaPlayer
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
var audioPlayer: AVAudioPlayer?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
let keyS = bestAttemptContent?.userInfo["type"] as? Int
if keyS == 2 {
let valueS = bestAttemptContent?.userInfo["amount"] as? String//金額
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "zh-CN")
formatter.allowsFloats = true
let strF: CGFloat = formatter.number(from: valueS ?? "0") as? CGFloat ?? 0.0
formatter.numberStyle = . spellOut
let resultS: String = formatter.string(from: NSNumber (value: strF)) ?? ""
let resultSA: Array<String> = resultS.map { String($0) }
var finalA: Array<String> = ["錢(qián)響", "哥小兔到賬"]
finalA.append(contentsOf: resultSA)
finalA.append("元")
mergeAVAsset(with: finalA) { (name,path) in
// NSLog("合并后的音頻路徑: \(path)")
let audioSession = AVAudioSession.sharedInstance()
do {//配置音頻触机,可以在后臺(tái)、靜音情況下播放
try audioSession.setCategory(.playback, mode:.default, options: [.mixWithOthers])
try audioSession.setActive(true)
} catch {
print("Error configuring audio session: \(error)")
}
self.audioPlayer = try? AVAudioPlayer(contentsOf: path ?? URL(fileURLWithPath: ""))
self.audioPlayer?.delegate = self
self.audioPlayer?.play()
}
} else {
if let bestAttemptContent = self.bestAttemptContent {
// Modify the notification content here...
// bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
contentHandler(bestAttemptContent)
}
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
//合成要播報(bào)的語(yǔ)音
func mergeAVAsset(with sourcePathArr: [String], rate: Double = 1.0, completed: @escaping (_ soundName: String?,_ soundsFileURL: URL?) -> Void) {
// 創(chuàng)建音頻軌道, 并獲取多個(gè)音頻素材的軌道
let composition = AVMutableComposition()
// 音頻插入的開(kāi)始時(shí)間, 用于記錄每次添加音頻文件的開(kāi)始時(shí)間
var beginTime = CMTime.zero
for audioFilePath in sourcePathArr {
// 獲取音頻素材
let audioFileURL: String = Bundle.main.path(forResource: audioFilePath, ofType: "mp3") ?? ""
guard let audioAsset = AVURLAsset(url: URL(fileURLWithPath: audioFileURL)) as AVAsset? else { continue }
// 音頻軌道
let audioTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)
// 獲取音頻素材軌道
guard let audioAssetTrack = audioAsset.tracks(withMediaType: .audio).first else { continue }
// 音頻合并 - 插入音軌文件
try? audioTrack?.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: audioAsset.duration), of: audioAssetTrack, at: beginTime)
// 記錄尾部時(shí)間
beginTime = CMTimeAdd(beginTime, audioAsset.duration)
}
let finalTimeValue = composition.duration.value * Int64(10 * rate)
let finalTimeScale = composition.duration.timescale * 10
composition.scaleTimeRange(.init(start: .zero, end: composition.duration), toDuration: .init(value: finalTimeValue, timescale: finalTimeScale))
let groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.自己項(xiàng)目的BundleIdentifier")
//建立文件夾
let soundsURL = groupURL?.appendingPathComponent("Library/", isDirectory: true)
let soundsURL2 = groupURL?.appendingPathComponent("Library/Sounds/", isDirectory: true)
do {
//建立文件夾
if !FileManager.default.fileExists(atPath: (soundsURL?.path ?? "")) {
try FileManager.default.createDirectory(atPath: (soundsURL?.path ?? ""), withIntermediateDirectories: true, attributes: nil)
}
//建立文件夾
if !FileManager.default.fileExists(atPath: (soundsURL2?.path ?? "")) {
try FileManager.default.createDirectory(atPath: (soundsURL2?.path ?? ""), withIntermediateDirectories: true, attributes: nil)
}
} catch {
print("Error 建立文件夾: \(error)")
}
// 新建文件名,如果存在就刪除舊的
let soundName = "sound.m4a"
let outPutFilePath = "Library/Sounds/" + soundName
let soundsFileURL = groupURL?.appendingPathComponent(outPutFilePath, isDirectory: false)
if FileManager.default.fileExists(atPath: (soundsFileURL?.path ?? "")) {
do {
try FileManager.default.removeItem(atPath:(soundsFileURL?.path ?? ""))
} catch {
print("Error 新建文件名儡首,如果存在就刪除舊的: \(error)")
}
}
// 導(dǎo)出合并后的音頻文件
guard let session = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A) else { completed(nil, nil); return }
// 音頻文件輸出
session.outputURL = soundsFileURL
session.outputFileType = AVFileType.m4a // 與上述的`preset`相對(duì)應(yīng)
session.shouldOptimizeForNetworkUse = true // 優(yōu)化網(wǎng)絡(luò)
// session.audioMix = videoAudioMixTools
session.exportAsynchronously {
if session.status == .completed {
// print("合并成功 ----\(soundsFileURL)")
completed(soundName, soundsFileURL)
} else {
// 其他情況, 具體請(qǐng)看這里`AVAssetExportSessionStatus`.
// print("合并失敗 ----\(session.status.rawValue)")
// print("合并失敗 ----\(session.error)")
completed(nil, nil)
}
}
}
}
extension NotificationService: AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
//播放結(jié)束片任,執(zhí)行contentHandler,結(jié)束這個(gè)通知
if (contentHandler != nil) && (bestAttemptContent != nil) {
bestAttemptContent?.sound = .none//因?yàn)橛姓Z(yǔ)音播報(bào)了蔬胯,這里把系統(tǒng)通知的聲音關(guān)了
contentHandler!(bestAttemptContent!)
}
}
}
像 哥小兔到賬.mp3对供、 元.mp3、 萬(wàn).mp3 這些語(yǔ)音文件氛濒,可以去ai語(yǔ)音合成产场,類(lèi)似的有:百度、科大訊飛舞竿、標(biāo)貝等
語(yǔ)音生成工具:標(biāo)貝悅讀京景、百度、科大訊飛
第三種
經(jīng)過(guò)查找骗奖,大概率支付寶确徙、微信使用的使用voip模式,通過(guò)查找微信與支付寶的ipa执桌,ipa中配置的文件都UIBackgroundModes(后臺(tái)模式)包含voip鄙皇。
所以大概率支付寶與微信都使用的是Voip PushKit實(shí)現(xiàn)的收款的語(yǔ)音播報(bào)功能
之后也會(huì)調(diào)查下Voip PushKit實(shí)現(xiàn)的收款的語(yǔ)音播報(bào)功能,PushKit和極光推送還不太一樣仰挣。持續(xù)關(guān)注中伴逸。。椎木。