iosswiftmp4avassetexportsessionm4a

AVAssetExportSession succeeds to convert mp4 to m4a on iPhone simulator but iPhone device


I'm trying to convert mp4 video file to m4a audio format by AVAssetExportSession on my iOS app.

This is the conversion code:

let outputUrl = URL(fileURLWithPath: NSTemporaryDirectory() + "out.m4a")
if FileManager.default.fileExists(atPath: outputUrl.path) {
    try? FileManager.default.removeItem(atPath: outputUrl.path)
}

let asset = AVURLAsset(url: inputUrl)
// tried the `AVAssetExportPresetAppleM4A` preset name but the same result
let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough)!
exportSession.outputFileType = AVFileType.m4a
exportSession.outputURL = outputUrl

await exportSession.export()
switch exportSession.status {
case .completed:
    return outputUrl
default:
    // This becomes `4` which is `.failed`
    print("Status: \(exportSession.status)")
    throw exportSession.error!
}

Currently, it seems to work on iPhone simulators (confirmed on iOS 16.1/15.5) but it doesn't on my iPhone 7 (iOS 15.7.1) real device. It doesn't seem to work as well on my colleague's iOS 16.1 real device, so it shouldn't be a matter of the iOS version.

The mp4 file is located in the iOS Files app and the inputUrl in the above code becomes something like this (I get this URL via UIDocumentPickerViewController):

and the error is:


Solution

  • It seems to be resolved by calling startAccessingSecurityScopedResource() to the inputUrl before exporting.

    inputUrl.startAccessingSecurityScopedResource()
    

    Not sure exactly why but that's probably because the inputUrl is under the file:///private namespace?