我正在开发一个可在设备震动时播放随机歌曲的应用程序。以下是我的代码
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if event?.subtype == UIEventSubtype.motionShake{
let soundArray=["firstsong","second","fourth"]
let randomNumber=Int(arc4random_uniform(UInt32(Int32(soundArray.count))))
let fileLocation = Bundle.main.path(forResource: soundArray[randomNumber], ofType: "mp3")
do {
try player=AVAudioPlayer(contentsOf:URL(fileURLWithPath:fileLocation!))
player.play()
}catch{
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我已将mp3文件放在音乐文件夹中。
当我摇晃设备时,出现以下错误
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
任何帮助将不胜感激
最佳答案
等待。您说过将文件放在音乐文件夹中?那么您的代码是错误的。您发布的代码尝试从您的应用程序包内部读取文件。您需要完全使用另一种方法来从用户的音乐文件夹中读取文件,并且需要编写该代码以检查文件是否存在,如果不存在则正常失败。
我建议将声音文件拖到Xcode项目中的“resources”文件夹中,并确保已选中文件复选框,以便将它们包含在应用程序包中。如果这样做,您的代码应该可以工作(但是您仍然应该检查nil而不是像上面我的评论中提到的那样使用强制展开)。
关于ios - 摇晃播放我的阵列列表中的随机歌曲时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47847470/