The app that I'm creating I'm trying to combine two audio files, one is larger than the other, I need the first one to run for a certain time and then the second, but all as one audio (the audio is playing while app is in the background)
Here is what I got so far
func merge(audio1: NSURL, audio2: NSURL, time:Double, date:NSDate) {
var ok1 = false
var ok2 = false
/
/
var composition = AVMutableComposition()
var compositionAudioTrack1:AVMutableCompositionTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
var compositionAudioTrack2:AVMutableCompositionTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
/
var documentDirectoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as! NSURL
var fileDestinationUrl = documentDirectoryURL.URLByAppendingPathComponent("resultmerge.wav")
println(fileDestinationUrl)
var url1 = audio1
var url2 = audio2
var avass = AV
var avAsset1 = AVURLAsset(URL: url1, options: nil)
var avAsset2 = AVURLAsset(URL: url2, options: nil)
var tracks1 = avAsset1.tracksWithMediaType(AVMediaTypeAudio)
var tracks2 = avAsset2.tracksWithMediaType(AVMediaTypeAudio)
var assetTrack1:AVAssetTrack = tracks1[0] as! AVAssetTrack
var assetTrack2:AVAssetTrack = tracks2[0] as! AVAssetTrack
var seconds = CMTimeMakeWithSeconds(time, Int32())
/
var duration2: CMTime = assetTrack2.timeRange.duration
var timeRange1 = CMTimeRangeMake(kCMTimeZero, seconds)
var timeRange2 = CMTimeRangeMake(seconds, duration2)
ok1 = compositionAudioTrack1.insertTimeRange(timeRange1, ofTrack: assetTrack1, atTime: kCMTimeZero, error: nil)
if ok1 {
ok2 = compositionAudioTrack2.insertTimeRange(timeRange2, ofTrack: assetTrack2, atTime: seconds, error: nil)
if ok2 {
println("success")
}
}
/
var assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)
assetExport.outputFileType = AVFileTypeAppleM4A
assetExport.outputURL = fileDestinationUrl
assetExport.exportAsynchronouslyWithCompletionHandler({
switch assetExport.status{
case AVAssetExportSessionStatus.Failed:
println("failed \(assetExport.error)")
case AVAssetExportSessionStatus.Cancelled:
println("cancelled \(assetExport.error)")
default:
println("complete")
var audioPlayer = AVAudioPlayer()
audioPlayer = AVAudioPlayer(contentsOfURL: fileDestinationUrl, error: nil)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
})
}
Is this the ideal way to do it? Also how do I convert mp3/m4a files into NSUrl's , I have local sound files that I need to convert into NSUrl for the function to work, how would i do that?