【发布时间】:2018-01-23 05:31:39
【问题描述】:
我正在处理一个必须播放用户自己录制的音频的项目。当应用程序第一次启动并且用户录制了一些音频时,当尝试播放它时,AVAudioPlayer 似乎正在播放但立即停止。如果用户尝试录制另一段音频,则 AVAudioPlayer 可以正常工作。
播放和停止音频的代码:
@objc func playAudio() {
if audioPlayer == nil {
do{
if FileManager.default.fileExists(atPath: filename.path) {
print("File Exists")
}
else {
print("File Doesnt Exists")
}
try audioPlayer = AVAudioPlayer(contentsOf: filename)
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
audioPlayer.play()
print(audioPlayer.isPlaying)
print("Playing Audio")
playStopButton.setImage(#imageLiteral(resourceName: "Stop Button"), for: .normal)
}catch {
//displayAlert(title: "Oops!", message: "There was an error. Try Recording Again")
print(error)
}
}
else {
playStopButton.setImage(#imageLiteral(resourceName: "Play Button"), for: .normal)
audioPlayer.stop()
audioPlayer = nil
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
if flag {
print("Stopping Cuase Comlete")
playStopButton.setImage(#imageLiteral(resourceName: "Play Button"), for: .normal)
audioPlayer.stop()
audioPlayer = nil
}
}
录音代码
@objc func record() {
if audioRecorder == nil{
let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey:1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue]
do{
audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
//view.backgroundColor = UIColor.red
//recordButton.setTitle("Stop Recording", for: .normal)
setupTimer()
timerDisplay.isHidden = false
shapeLayer.fillColor = UIColor.black.cgColor
}catch{
displayAlert(title: "Oops!", message: "Recording Failed")
}
}
else{
audioRecorder.stop()
timer?.invalidate()
timer = nil
shapeLayer.strokeEnd = 0
audioRecorder=nil;
timerDisplay.isHidden = true
shapeLayer.fillColor = UIColor.red.cgColor
let selected = arr[picker.selectedRow(inComponent: 0)]
UserDefaults.standard.set(selected, forKey: "SelectedTopic")
present(UINavigationController(rootViewController: PlaybackController()), animated: true, completion: nil)
}
}
【问题讨论】:
-
检查第一次提供的路径是否正确?
-
@iOSGeek 是的,它每次都返回文件存在的 true
-
我没有看到任何错误 如果提供的文件名不正确,它可能会发生,因为第二次它工作正常,很难发现错误
-
@iOSGeek 不能是文件名每次文件名都一样
-
我也遇到了同样的问题,你找到解决办法了吗?
标签: ios swift audio avaudioplayer avaudiorecorder