Recording gapless audio with AVAssetWriter

后端 未结 2 1192
北荒
北荒 2021-02-09 23:21

I\'m trying to record segments of audio and recombine them without producing a gap in audio.

The eventual goal is to also have video, but I\'ve found that audio itself c

2条回答
  •  孤街浪徒
    2021-02-10 00:12

    Not sure if this helps you but if you have a bunch of MP4s you can use this code to combine them:

    func mergeAudioFiles(audioFileUrls: NSArray, callback: (url: NSURL?, error: NSError?)->()) {
    
        // Create the audio composition
        let composition = AVMutableComposition()
    
        // Merge
        for (var i = 0; i < audioFileUrls.count; i++) {
    
            let compositionAudioTrack :AVMutableCompositionTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
    
            let asset = AVURLAsset(URL: audioFileUrls[i] as! NSURL)
    
            let track = asset.tracksWithMediaType(AVMediaTypeAudio)[0]
    
            let timeRange = CMTimeRange(start: CMTimeMake(0, 600), duration: track.timeRange.duration)
    
            try! compositionAudioTrack.insertTimeRange(timeRange, ofTrack: track, atTime: composition.duration)
        }
    
        // Create output url
        let format = NSDateFormatter()
        format.dateFormat="yyyy-MM-dd-HH-mm-ss"
        let currentFileName = "recording-\(format.stringFromDate(NSDate()))-merge.m4a"
        print(currentFileName)
    
        let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
        let outputUrl = documentsDirectory.URLByAppendingPathComponent(currentFileName)
        print(outputUrl.absoluteString)
    
        // Export it
        let assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)
        assetExport?.outputFileType = AVFileTypeAppleM4A
        assetExport?.outputURL = outputUrl
    
        assetExport?.exportAsynchronouslyWithCompletionHandler({ () -> Void in
            switch assetExport!.status {
                case AVAssetExportSessionStatus.Failed:
                    callback(url: nil, error: assetExport?.error)
                default:
                    callback(url: assetExport?.outputURL, error: nil)
            }
        })
    
    }
    

提交回复
热议问题