我正在考虑一个 iOS 警报应用程序。在闹钟响起时,我想播放来自 Apple Music 或其他来源的自定义音乐。
不幸的是,应用程序后台操作非常严格,通知只允许播放捆绑的音乐文件。有没有办法通过使用后台任务或其他方式来实现我的目标?
我正在考虑一个 iOS 警报应用程序。在闹钟响起时,我想播放来自 Apple Music 或其他来源的自定义音乐。
不幸的是,应用程序后台操作非常严格,通知只允许播放捆绑的音乐文件。有没有办法通过使用后台任务或其他方式来实现我的目标?
除了使用通知之外没有其他选择,另请参阅:后台执行
访问 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
则为 nil。
使用文件共享
如何为我的应用启用文件共享
因为通知是有限的: 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)
})
}
}
注意:自定义音频文件只能放在/Library/Sounds
App 的Sandbox中,而不是soundName
只需要提供文件名(包括扩展名),音频文件就像在主包中一样。
这是来自 github.com/ToFind1991 的演示
代码与当前 Swift 版本不兼容,需要调整。