我已成功录制并播放本地通知声音的声音,并且在调用该功能时也会播放。
但问题是当我给声音属性提供声音链接时,它不起作用。
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设置通知自定义声音?
答案 0 :(得分:0)
根据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)
}
}