【问题标题】:Local notification custom sound from URL iOS Swift来自 URL iOS Swift 的本地通知自定义声音
【发布时间】:2018-04-11 15:55:41
【问题描述】:

我已经成功录制并播放了本地通知声音的声音,并且在调用该函数时也会播放。

但问题是当我将声音的链接提供给通知声音属性时,它不起作用。

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 设置通知自定义声音?

【问题讨论】:

    标签: ios swift usernotifications


    【解决方案1】:

    根据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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 2011-11-02
      • 2021-04-05
      • 1970-01-01
      相关资源
      最近更新 更多