音频到视频转换为swift

时间:2016-07-12 08:44:11

标签: swift

我设法使用NSUrlConnection下载音频并将其保存到设备中。现在我想将此(我猜.mp3)文件转换为.mp4视频文件。

1 个答案:

答案 0 :(得分:-1)

我有解决方案

    let soundFileUrl = audioURL
    let recordAsset: AVURLAsset = AVURLAsset(URL: soundFileUrl, options: nil)

    let mixComposition: AVMutableComposition = AVMutableComposition()
    let recordTrack: AVMutableCompositionTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())

    let tracks1 =  recordAsset.tracksWithMediaType(AVMediaTypeAudio)
    let assetTrack1:AVAssetTrack = tracks1[0]

    let audioDuration:CMTime = assetTrack1.timeRange.duration
    do
    {
        try recordTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, audioDuration), ofTrack: assetTrack1, atTime: kCMTimeZero)

    } catch {
    }

    let assetExport = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetPassthrough)!
    assetExport.outputFileType = AVFileTypeQuickTimeMovie
    assetExport.outputURL = savePathUrl
    assetExport.shouldOptimizeForNetworkUse = true

    assetExport.exportAsynchronouslyWithCompletionHandler( {

        switch assetExport.status {
        case  AVAssetExportSessionStatus.Failed:
            print("failed \(assetExport.error)")
        case AVAssetExportSessionStatus.Cancelled:
            print("cancelled \(assetExport.error)")
        default:
            print("complete\(savePathUrl)")
        }
    })