기기 흔들기에서 임의의 노래를 재생하는 앱을 개발 중입니다. 다음은 내가 음악 폴더에 내 mp3 파일을 배치 한 내 코드흔들어서 내 배열 목록에서 임의의 노래를 재생할 때 예외가 발생했습니다.
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.
}
}
입니다. 내가 장치를 흔들 때 은 내가 어떤 도움이 크게 될
자, 코드를 디버깅해야합니다. 지역 변수로 작은 단계로 나누고 함수의 맨 위에 중단 점을 설정 한 다음 단계별로 각 행의 결과를 검토하십시오. 내 돈은'fileLocation! '이라는 표현입니다. fileLocation이 nil이면 충돌합니다. (force-unwrap 연산자를 "nil if crash"연산자라고 부르겠습니다. 실제로 무엇을하는지 알 때까지는이를 피하십시오.) –