[英]Local notification custom sound from URL iOS Swift
我已經成功錄制並播放了本地通知聲音,並且在調用該功能時也能播放。
但是問題是當我將聲音的鏈接賦予通知聲音屬性時,它不起作用。
notification.sound = UNNotificationSound.init(named: "martian-gun copy.m4a")
上面的代碼工作完美。 但是當我給它URL(以字符串形式)時,它並沒有播放確切的聲音。 代碼不起作用如下:
let fm = FileManager.default
let docsurl = try! fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let myurl = docsurl.appendingPathComponent("sound.m4a")
notification.sound = UNNotificationSound.init(named: myurl)
myurl具有在playButton上播放聲音的相同路徑。 最后一個問題是如何從聲音URL設置通知自定義聲音?
根據UNNotificationSound
的文檔,您需要將音頻文件的副本放置在應用程序容器目錄的Library/Sounds
文件夾中。
let docsurl = try FileManager.default.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let myurl = docsurl.appendingPathComponent("sound.m4a")
let filename = myurl.lastPathComponent
let targetURL = try FileManager.default.soundsLibraryURL(for: filename)
// copy audio file to /Library/Sounds
if !FileManager.default.fileExists(atPath: targetURL.path) {
try FileManager.default.copyItem(at: sourceURL, to: targetURL)
}
let content = UNMutableNotificationContent()
content.sound = UNNotificationSound(named: UNNotificationSoundName(filename))
extension FileManager {
func soundsLibraryURL(for filename: String) throws -> URL {
let libraryURL = try url(for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let soundFolderURL = libraryURL.appendingPathComponent("Sounds", isDirectory: true)
if !fileExists(atPath: soundFolderURL.path) {
try createDirectory(at: soundFolderURL, withIntermediateDirectories: true)
}
return soundFolderURL.appendingPathComponent(filename, isDirectory: false)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.