【问题标题】:non-main bundle file as alert sound非主捆绑文件作为警报声音
【发布时间】:2012-07-30 01:14:42
【问题描述】:

我希望我错了,但我认为这不可能。在本地和推送通知编程指南中,在“准备自定义警报声音”下它说“声音文件必须在客户端应用程序的主包中”。

如果您无法写入主包,那么如何让用户生成的录音(例如,使用 AVAudioRecorder)作为警报声音播放?

一方面这似乎不可能,但另一方面我认为那里有应用程序可以做到这一点(我会寻找那些)。

【问题讨论】:

  • 好吧,我找到了一个可以做到这一点的应用程序:VoCal XL。有什么想法吗?
  • 可能是文档有误,声音文件不必在应用程序包中,而是在应用程序沙箱中。
  • 嗯。我已经测试过了,它不起作用。但是,如果我使用通过 Xcode 加载的声音(即在主包中),那么它确实有效,让我相信文档是正确的。关于如何测试事物的任何想法?

标签: ios uilocalnotification avaudiorecorder


【解决方案1】:

我通过将系统声音文件复制到 ~/Library/Sounds 目录并将其命名为 notification.caf 来解决此问题。服务器警报负载将此指定为要播放的声音的名称。每当用户选择另一个声音时,该声音将被复制到同一文件夹并覆盖旧声音。

有效载荷:

{
"aps": {
    "sound": "notification.caf"
}

}

// get the list of system sounds, there are other sounds in folders beside /New
let soundPath = "/System/Library/Audio/UISounds/New"
func getSoundList() -> [String] {
    var result:[String] = []
    let fileManager = NSFileManager.defaultManager()
    let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(soundPath)!
    for url in enumerator.allObjects {
        let string = url as! String
        let newString = string.stringByReplacingOccurrencesOfString(".caf", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
        result.append(newString)
    }
    return result
}

// copy sound file to /Library/Sounds directory, it will be auto detect and played when a push notification arrive
class func copyFileToDirectory(fromPath:String, fileName:String) {
    let fileManager = NSFileManager.defaultManager()

    do {
        let libraryDir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask, true)
        let directoryPath = "\(libraryDir.first!)/Sounds"
        try fileManager.createDirectoryAtPath(directoryPath, withIntermediateDirectories: true, attributes: nil)

        let systemSoundPath = "\(fromPath)/\(fileName)"
        let notificationSoundPath = "\(directoryPath)/notification.caf"

        let fileExist = fileManager.fileExistsAtPath(notificationSoundPath)
        if (fileExist) {
            try fileManager.removeItemAtPath(notificationSoundPath)
        }
        try fileManager.copyItemAtPath(systemSoundPath, toPath: notificationSoundPath)
    }
    catch let error as NSError {
        print("Error: \(error)")
    }
}

虽然推送通知的声音可能有问题,但我必须重启手机才能可靠地播放每个通知。

【讨论】:

  • 你是怎么解决这个问题的?我做了和你一样的过程,但是每当我发送推送通知时,如果应用程序处于活动状态或在后台,iphone的整个音响系统都会崩溃,如果应用程序没有运行,那么通知声音播放没有问题,我不明白原因但是如果 ios 想在应用程序处于活动状态时播放库文件夹中的声音文件,那么您甚至无法设置 iphone 的音量,直到您在另一个应用程序(如 Spotify 等)中播放歌曲,然后它恢复正常
猜你喜欢
  • 2022-08-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多