簡體   English   中英

來自URL iOS Swift的本地通知自定義聲音

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM