Reputation: 890
The layout of project architecture:
record audio -> trim audio -> play trimmed audio -> upload to server.
I'm having troubles with playback of audio file that is created as a result of AVAssetExportSession trimming. I had doubts about integrity of trimmed file and I've uploaded it to server and there it plays fine, but iOS refuses to play it. I init AVAudioPlayer with URL to trimmed file, then play() and nothing happens, not even errors are thrown.
Please see code below, what can cause the problem?
static func outputFileURL() -> URL {
let outputFileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.path.appending("/audioRecord-trimmed.m4a")
return URL(fileURLWithPath: outputFileURL)
}
@IBAction func trimRecording(_ sender: RoundCornerButton) {
//Delete existing recording
deleteEditedRecording()
//Check duration
let duration = CMTimeGetSeconds(recordingToTrim.duration)
if (duration < 5.0) {
let alertController = UIAlertController(title: "Warning", message: "Sound is too short", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
return
} else {
let exporter = AVAssetExportSession(asset: recordingToTrim, presetName: AVAssetExportPresetAppleM4A)
exporter?.outputFileType = AVFileTypeAppleM4A
exporter?.outputURL = EditorVC.outputFileURL()
exporter?.timeRange = durationToTrim!
exporter?.exportAsynchronously(completionHandler: {
if exporter?.status == .completed {
let alertController = UIAlertController(title: "Success", message: nil, preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
} else {
let alertController = UIAlertController(title: "Error", message: exporter?.error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
print(exporter?.error?.localizedDescription)
print("Export failed")
return
}
})
}
}
@IBAction func playTrimmedAudio(_ sender: RoundCornerButton) {
print("\nPlay tap\n")
let player = try! AVAudioPlayer(contentsOf: EditorVC.outputFileURL())
player.play()
}
Upvotes: 1
Views: 97
Reputation: 434
declare audio player globally like this :
var player:AVAudioPlayer!
in your playTrimmedAudio function add this two line of code
player = try! AVAudioPlayer(contentsOf: EditorVC.outputFileURL())
player.play()
Upvotes: 1