【问题标题】:iOS Music started from backgroundiOS 音乐从后台开始
【发布时间】:2018-08-27 09:40:49
【问题描述】:

我正在考虑一个 iOS 警报应用程序。在闹钟响起时,我想播放来自 Apple Music 或其他来源的自定义音乐。

不幸的是,应用程序后台操作非常严格,通知仅允许播放捆绑的音乐文件。有没有办法通过使用后台任务或其他方式来实现我的目标?

【问题讨论】:

  • 您可以尝试从您的应用程序中在提醒应用程序中设置警报,即使您的应用程序处于后台模式或暂停或终止......也会运行提醒应用程序的音乐......

标签: ios alarm ios-background-mode


【解决方案1】:

除了使用通知没有其他选择,另见:Background Execution

更改通知的声音。

1。导入音频文件。

  • 访问 iPod 音乐库

    let mediaquery = MPMediaQuery()
    // MPMusicPlayerControllerNowPlayingItemDidChangeNotification
    if let musics = mediaquery.items {
        for music in musics {
            let title = music.valueForProperty(MPMediaItemPropertyTitle) as? String
    
            if let url = music.assetURL {
                saveNotificationSound(url,name: title,isLast: music == musics.last)
            }
        }
    }
    

    重要的参数是assetURL,你可以通过它获取音频文件。 注意:如果音乐是从 Apple Music 或 iCloud 下载的,则 assertURL 为零。

  • 使用文件共享
    How to enable file sharing for my App

2。将音频剪切到 30 秒并指定通知格式

因为通知是有限的: 1. 时长不超过30s; 2. 格式有限,剪成m4a

/**
 Cut the duration and convert to m4a, than save it. 

 - parameter audioPath:  Source file path 
 - parameter startTime:  Cut start time
 - parameter endTime:    Cut end time 
 - parameter saveDirect: ... 
 - parameter handler:    ...
 */
func cutoffAudio(audioPath: NSURL, startTime: Int64, endTime: Int64, saveDirect:NSURL, handler: (succeed: Bool) -> Void){

    let audioAsset = AVURLAsset(URL: audioPath, options: nil)

    if let exportSession = AVAssetExportSession(asset: audioAsset, presetName: AVAssetExportPresetAppleM4A){

        let startTime = CMTimeMake(startTime, 1)
        let stopTime = CMTimeMake(endTime, 1)

        exportSession.outputURL = saveDirect
        // Output is m4a
        exportSession.outputFileType = AVFileTypeAppleM4A
        exportSession.timeRange = CMTimeRangeFromTimeToTime(startTime, stopTime)

        exportSession.exportAsynchronouslyWithCompletionHandler({ 
            handler(succeed: exportSession.status == .Completed)
        })
    }
}

3。设置为通知的声音

注意:自定义音频文件只能放在A​​pp的沙盒/Library/Sounds,而不是soundName只需要提供文件名(包括扩展名),音频文件就像在主包中一样。

Here is a demo from github.com/ToFind1991

代码与当前 Swift 版本不兼容,需要调整。

【讨论】:

  • 好的,也就是说它只适用于 UNNotificationRequest 和捆绑的音乐文件?
  • 您可以通过音频文件更改通知声音。 @user1517039
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 2014-09-05
相关资源
最近更新 更多