I am trying to export a .wav file from a video file extracted from a UIImagePickerController
UIImagePickerController.InfoKey.mediaURL
Example url passed in to the function:
file:///private/var/mobile/Containers/Data/PluginKitPlugin/BCE1C3A1-AA62-4D89-9487-05E19DB476A7/tmp/trim.3C31A33B-A99E-45B7-9101-5C225CFCFF2B.MOV
I am able to sucesfully use this function to extract a m4a file but I cannot get it to work with a WAV file. The error I get running the code below is, "Audio extraction as WAV failed with error: Operation Stopped"
I do not know why I am getting "Operation Stopped" error on a wav file and not a m4a? An alternative I have tried is converting a m4a to wav after the fact and get the same error...
func extractAudioAsWAV(from mediaURL: URL) {
let inputAsset = AVAsset(url: mediaURL)
let outputFilePath = URL(fileURLWithPath: NSTemporaryDirectory() + "out.wav")
let audioAsset = inputAsset.tracks(withMediaType: .audio).first
if let audioAsset = audioAsset {
let composition = AVMutableComposition()
let audioTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)
do {
try audioTrack?.insertTimeRange(CMTimeRange(start: CMTime.zero, duration: inputAsset.duration), of: audioAsset, at: CMTime.zero)
let exportSession = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetPassthrough)
exportSession?.outputFileType = AVFileType.wav
exportSession?.outputURL = URL(fileURLWithPath: outputFilePath.absoluteString)
exportSession?.exportAsynchronously(completionHandler: {
if exportSession?.status == .completed {
print("Audio extraction as WAV completed.")
} else if let error = exportSession?.error {
print("Audio extraction as WAV failed with error: \(error.localizedDescription)")
}
})
} catch {
print("Error: \(error.localizedDescription)")
}
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as? NSURL
self.dismiss(animated: true, completion: nil)
extractAudioAsWAV(from: videoURL! as URL)
}
func presentImagePicker() {
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
imagePickerController.mediaTypes = ["public.movie"]
present(imagePickerController, animated: true, completion: nil)
}
The function (extractAudioAsWAV) above works by changing these lines of code for an m4a rather than a wav:
let outputFilePath = URL(fileURLWithPath: NSTemporaryDirectory() + "out.m4a")
exportSession?.outputFileType = AVFileType.m4a