There're no other choices except using notifications, seealso: Background Execution
Change the sound of notification.
1. Import audio files.
Visit the iPod music library
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)
}
}
}
The important param is assetURL
, you can get audio file by it. NOTICE: If the music is download from Apple Music or in the iCloud, it's assertURL
is nil.
Use file sharing
How to enable file sharing for my App
2. Cut the audio to 30s and specified format for notification
Because the notification is limited: 1. The duration is not more than 30s; 2. The format is limited, we cut it to 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. Set as the sound of notification
Attention: The custom audio files can only be placed in /Library/Sounds
in App's Sandbox, than the soundName
only needs to provide the file name (including the extension), the audio files are just like in the main bundle.
Here is a demo from github.com/ToFind1991
The code is not compatible with the current Swift version, you need to adjust it.