ios – 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
    // 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):

  • file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/Downloads/%E3%81%8A%E3%81%97%E3%82%83%E3%81%B8%E3%82%99%E3%82%8A%E3%81%B2%E3%82%8D%E3%82%86%E3%81%8D.mp4

and the error is:

  • Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSUnderlyingError=0x2808f30c0 {Error Domain=NSOSStatusErrorDomain Code=-16979 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-16979), NSLocalizedRecoverySuggestion=XXXXDEFAULTVALUEXXXX, NSURL=file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/Downloads/%E3%81%8A%E3%81%97%E3%82%83%E3%81%B8%E3%82%99%E3%82%8A%E3%81%B2%E3%82%8D%E3%82%86%E3%81%8D.mp4, NSLocalizedDescription=The operation could not be completed}