swift 如何将 .caf 音频文件转换为 .mp4 文件

How to convert .caf Audio file into .mp4 file in swift

我正在使用带有 AVAudioRecorder 的设备麦克风录制音频,其中 return 文件采用 .caf 格式,只能在 Apple 设备上播放,但不能在Android 台设备。由于苹果不支持 .mp3 文件,所以我想在上传到服务器之前将其转换为 .mp4 格式。 .mp4 是否仅适用于音频?我可以用 AVAssetExportSession 转换吗?

以下是录音机代码:

func setupAudioRecorder ()
    {

    let fileMgr = FileManager.default
    let dirPaths = fileMgr.urls(for:.documentDirectory,
                                in:.userDomainMask)

    let soundFileURL = dirPaths[0].appendingPathComponent("myaudio.caf")

    let recordSettings =
        [AVEncoderAudioQualityKey: AVAudioQuality.min.rawValue,
         AVEncoderBitRateKey: 16,
         AVNumberOfChannelsKey: 2,
         AVSampleRateKey: 44100.0] as [String : Any]

    do {
        try audioSession.setCategory(
            AVAudioSessionCategoryPlayAndRecord)
    } catch let error as NSError {
        print("audioSession error: \(error.localizedDescription)")
    }

    do {
        try audioRecorder = AVAudioRecorder(url: soundFileURL,
                                            settings: recordSettings as [String : AnyObject])
        audioRecorder?.prepareToRecord()
    } catch let error as NSError {
        print("audioSession error: \(error.localizedDescription)")
    }
}

您可以直接录制 MPEG4 AAC,无需额外的转换步骤。使用 AVFormatIDKeykAudioFormatMPEG4AAC 值并将采样率降低到 8000 或 16000。

经过大量搜索,我能够使用这段代码

.caf转换为.mp4
    let audioURL = ".caf audio file url"

    let fileMgr = FileManager.default

    let dirPaths = fileMgr.urls(for: .documentDirectory,
                                in: .userDomainMask)

    let outputUrl = dirPaths[0].appendingPathComponent("audiosound.mp4")

    let asset = AVAsset.init(url: audioURL)

    let exportSession = AVAssetExportSession.init(asset: asset, presetName: AVAssetExportPresetHighestQuality)

    // remove file if already exits
    let fileManager = FileManager.default
    do{
        try? fileManager.removeItem(at: outputUrl)

    }catch{
        print("can't")
    }


    exportSession?.outputFileType = AVFileTypeMPEG4

    exportSession?.outputURL = outputUrl

    exportSession?.metadata = asset.metadata

    exportSession?.exportAsynchronously(completionHandler: {
        if (exportSession?.status == .completed)
        {
            print("AV export succeeded.")

           // outputUrl to post Audio on server

        }
        else if (exportSession?.status == .cancelled)
        {
            print("AV export cancelled.")
        }
        else
        {
            print ("Error is \(String(describing: exportSession?.error))")

        }
    })