我正在尝试创建一个只记录和播放音频的应用。我尝试了多种不同的播放音频的方法,但在iPhone 6和iPhone 8 Plus上播放时似乎不起作用,但在模拟器上工作。
错误:
线程1:致命错误:在解包可选值时意外发现nil
当SoundPlayer尝试播放时会发生这种情况。控制台中打印的错误是:
错误域= NSOSStatusErrorDomain代码= 2003334207"(null)"
@IBOutlet weak var recordBtn: UIButton!
@IBOutlet weak var playBtn: UIButton!
var soundRecorder : AVAudioRecorder!
var soundPlayer : AVAudioPlayer!
var fileName = "audioFile0.aac"
var screenCounter = 0(全局变量)
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override open func viewDidLoad() {
super.viewDidLoad()
if (screenCounter == 0){
// Do any additional setup after loading the view, typically from a nib.
setupRecorder()
screenCounter += 1
}
}
func setupRecorder(){
let recordSettings = [ AVFormatIDKey : kAudioFormatMPEG4AAC
, AVEncoderAudioQualityKey : AVAudioQuality.max.rawValue, AVEncoderBitRateKey : 320000, AVNumberOfChannelsKey : 2, AVSampleRateKey : 44100.0 ] as [String : Any]
let _ : NSError?
do{
soundRecorder = try AVAudioRecorder(url : getFileURL() as URL, settings : recordSettings)
}catch{
print("Something went wrong")
}
soundRecorder.delegate = self
soundRecorder.prepareToRecord()
}
func getCacheDirectory() -> String{
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
return paths[0]
}
func getFileURL() -> NSURL{
let pathURL = NSURL(fileURLWithPath : getCacheDirectory()).appendingPathComponent(fileName)
let pathString = pathURL?.path
let filePath = NSURL(fileURLWithPath : pathString!)
return filePath
}
@IBAction func record(_ sender: UIButton) {
if sender.titleLabel?.text == "Record"{
soundRecorder.record()
sender.setTitle("Stop", for : .normal)
playBtn.isEnabled = false
}else{
soundRecorder.stop()
sender.setTitle("Record", for : .normal)
playBtn.isEnabled = false
}
}
@IBAction func playSound(_ sender: UIButton) {
if sender.titleLabel?.text == "Play"{
recordBtn.isEnabled = false
sender.setTitle("Stop", for : .normal)
preparePlayer()
soundPlayer.play()
}else{
soundPlayer.stop()
sender.setTitle("Play", for : .normal)
}
}
func preparePlayer(){
let _ : NSError?
do{
soundPlayer = try AVAudioPlayer(contentsOf : getFileURL() as URL)
}catch{
print(error)
}
soundPlayer.delegate = self
soundPlayer.prepareToPlay()
soundPlayer.volume = 1.0
}
open func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
playBtn.isEnabled = true
}
open func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
recordBtn.isEnabled = true
playBtn.setTitle("Play", for : .normal)
}
非常感谢任何帮助。
更新
感谢你的所有建议!我最终在另一个论坛here上找到了错误。在录制和播放称为音频会话的音频之间,似乎需要有中介。
答案 0 :(得分:1)
尝试在playSoung方法之外初始化soundPlayer。
var soundPlayer = AVAudioPlayer()
func preparePlayer() {
...
}
答案 1 :(得分:1)
It seems that audio file url is nil. Would you try with this FileManager
//func to give path(URL) to store the recording
func getDirectory() -> URL {
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let docDirectory = path[0]
return docDirectory
}
And your file URL full path should be:
let path = getDirectory().appendingPathComponent(fileName)
NOTE: As I could not run and test your code, I am not sure of the solution. Let me know the result. Otherwise, I will delete my post.