-
-
Save hanleyhansen/742beea8a6fc88d6254c611e5183dbdb to your computer and use it in GitHub Desktop.
Misuero Karoake Latino Recording Feature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let video = AVAsset(URL: currentCacheUrl) | |
let audioRecording = AVAsset(URL: currentRecordingUrl) | |
// 1 - Create AVMutableComposition object. This object will hold your AVMutableCompositionTrack instances. | |
let mixComposition = AVMutableComposition() | |
// 2 - Video track | |
let videoTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid) | |
do { | |
try videoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, audioRecording.duration), | |
ofTrack: video.tracksWithMediaType(AVMediaTypeVideo)[0], | |
atTime: kCMTimeZero) | |
} catch _ { | |
print("Failed to load video track") | |
} | |
// 3 - Audio track | |
let audioTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: 0) | |
do { | |
try audioTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, audioRecording.duration), | |
ofTrack: audioRecording.tracksWithMediaType(AVMediaTypeAudio)[0], | |
atTime: kCMTimeZero) | |
} catch _ { | |
print("Failed to load audio track") | |
} | |
// 4 - Get path | |
let recordingsPath = MisueroKaraokeLatinoHelper.Variables.getRecordingsDirectory | |
let currentDate = NSDate() | |
let date = formatDate(currentDate) | |
let savePath = recordingsPath.URLByAppendingPathComponent("\(date).mov") | |
// 5 - Create Exporter | |
guard let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality) else { return } | |
exporter.outputURL = savePath | |
exporter.outputFileType = AVFileTypeQuickTimeMovie | |
exporter.shouldOptimizeForNetworkUse = true | |
// 6 - Perform the Export | |
exporter.exportAsynchronouslyWithCompletionHandler() { | |
dispatch_async(dispatch_get_main_queue()) { _ in | |
print("save and merge complete") | |
let recording = Recording(title: self.currentRecordSong.title, artist: self.currentRecordSong.artist, genre: self.currentRecordSong.genre, timestamp: currentDate, fileUrl: savePath) | |
MisueroKaraokeLatinoHelper.Variables.Recordings.append(recording) | |
MisueroKaraokeLatinoHelper.Variables.Recordings.sortInPlace({$0.timestamp.compare($1.timestamp) == NSComparisonResult.OrderedDescending}) | |
let recordingsData = NSKeyedArchiver.archivedDataWithRootObject(MisueroKaraokeLatinoHelper.Variables.Recordings) | |
NSUserDefaults.standardUserDefaults().setObject(recordingsData, forKey: "Recordings") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment