我正在考虑使用iOS闹钟应用。发生警报时,我想播放Apple Music或其他来源的自定义音乐。
不幸的是,应用程序的后台操作确实很严格,并且通知仅允许播放捆绑的音乐文件。有什么方法可以通过使用后台任务或其他方法来实现我的目标?
答案 0 :(得分:0)
除了使用通知外,没有其他选择,另请参见:Background Execution
访问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
为零。
由于通知的限制: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)
})
}
}
注意:自定义音频文件只能放置在App的沙箱中的/Library/Sounds
中,而soundName
仅需要提供文件名称(包括扩展名),音频文件就像主捆绑中的文件一样。
Here is a demo from github.com/ToFind1991
该代码与当前的Swift版本不兼容,您需要对其进行调整。