项目架构的布局:
录制音频 - >修剪音频 - >播放修剪过的音频 - >上传到服务器。
我在播放因AVAssetExportSession修剪而创建的音频文件时遇到了麻烦。我对修剪过的文件的完整性有疑问,我已将其上传到服务器,并且它播放正常,但iOS拒绝播放它。我初始化AVAudioPlayer带有修剪文件的URL,然后播放()并且没有任何反应,甚至不会抛出错误。
请参阅下面的代码,可能导致什么问题?
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()
}
答案 0 :(得分:1)
像这样全局声明音频播放器:
var player:AVAudioPlayer!
在你的playTrimmedAudio函数中添加这两行代码
player = try! AVAudioPlayer(contentsOf: EditorVC.outputFileURL())
player.play()