iOS音乐从背景开始

时间:2018-08-27 09:40:49

标签: ios alarm ios-background-mode

我正在考虑使用iOS闹钟应用。发生警报时,我想播放Apple Music或其他来源的自定义音乐。

不幸的是,应用程序的后台操作确实很严格,并且通知仅允许播放捆绑的音乐文件。有什么方法可以通过使用后台任务或其他方法来实现我的目标?

1 个答案:

答案 0 :(得分:0)

除了使用通知外,没有其他选择,另请参见: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。设置为通知声音

注意:自定义音频文件只能放置在App的沙箱中的/Library/Sounds中,而soundName仅需要提供文件名称(包括扩展名),音频文件就像主捆绑中的文件一样。

Here is a demo from github.com/ToFind1991

该代码与当前的Swift版本不兼容,您需要对其进行调整。

相关问题