0

I managed it to download a audio using NSUrlConnection and save it to the device. Now I want to convert this (I guess .mp3) file to an .mp4 video file.

1 Answers1

2

i Got the solution

    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)")
        }
    })
  • This answer is partially correct. I upvoted it because the resulting video played inside the Files app. The problem came afterwards when I tried to play the video inside the Photos Library -it doesn't work. Please read here https://stackoverflow.com/q/71182543/4833705. The answer to question explains the issue https://stackoverflow.com/a/71187603/4833705 – Lance Samaria Feb 19 '22 at 18:05