使用AVMutableCompositionTrack合并/混合两个音频的问题

时间:2016-10-01 14:37:02

标签: ios swift xcode

当我尝试播放合并音频

时崩溃

我正在尝试合并两个音频文件。他们成功合并,但我看到一个问题,当我用AVAudioPlayer播放音频时,它会崩溃。格式也存在问题,因为合并音频仅以.m4a格式存储,如果我以.wav格式保存该音频,则会崩溃。

func merge(audio1:NSURL,audio2:NSURL){

让finalURL = getMergeFileURL()

    let preferredTimeScale : Int32 = 100

    //This object will be edited to include both audio files
    let composition = AVMutableComposition()

    let compositionAudioTrack1:AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
    //let url1 = audio1
    let avAsset1 = AVURLAsset(url: audio1 as URL, options: nil)
    let tracks1 =  avAsset1.tracks(withMediaType: AVMediaTypeAudio)
    let assetTrack1:AVAssetTrack = tracks1[0]
    let duration1: CMTime = CMTimeMakeWithSeconds(30.0, preferredTimeScale)
    let startCMTime = CMTimeMakeWithSeconds(Double(30.0), preferredTimeScale)
    let timeRange1 = CMTimeRangeMake(startCMTime, duration1)

    let compositionAudioTrack2:AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
    //let url2 = audio2
    let avAsset2 = AVURLAsset(url: audio2 as URL, options: nil)
    let tracks2 =  avAsset2.tracks(withMediaType: AVMediaTypeAudio)
    let assetTrack2:AVAssetTrack = tracks2[0]
    let duration2: CMTime = CMTimeMakeWithSeconds(30.0, preferredTimeScale)
    let startCMTime2 = CMTimeMakeWithSeconds(Double(30.0), preferredTimeScale)
    let timeRange2 = CMTimeRangeMake(startCMTime, duration1)


    //Insert the tracks into the composition
    do {

        try compositionAudioTrack1.insertTimeRange(timeRange1, of: assetTrack1, at: kCMTimeZero)

        try compositionAudioTrack2.insertTimeRange(timeRange2, of: assetTrack2, at: duration1)


    } catch {

        print(error)

    }

    //Perform the merge
    let assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)
    assetExport!.outputFileType = AVFileTypeAppleM4A
    assetExport!.outputURL = finalURL as URL // final url is the url of that merged file 
    assetExport!.exportAsynchronously(completionHandler: {
        switch assetExport!.status{
        case  AVAssetExportSessionStatus.failed:
            print("failed \(assetExport!.error)")
        case AVAssetExportSessionStatus.cancelled:
            print("cancelled \(assetExport!.error)")
        default:
            print("complete")

        }

    })

}

0 个答案:

没有答案