2017-10-18 30 views
-2

在一個項目上工作時,我決定添加一些音樂來播放特定動作。下面是我有:在Swift中播放音樂:意外地發現零,同時展開一個可選值

var player : AVAudioPlayer? 

幾行後...

func playSound(){ 
    let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "Kalimba", ofType: "wav")!) 
    print(alertSound) 

    try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) 
    try! AVAudioSession.sharedInstance().setActive(true) 

    try! player = AVAudioPlayer(contentsOf: alertSound) 
    player!.prepareToPlay() 
    player!.play() 
} 

每當我試試這個,Xcode中拋出我的時候,動作被觸發,說一個致命的錯誤:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

+0

你讓你的播放器一個可選值。然後強制使用播放器? –

+0

[如何在Swift中播放聲音?](https://stackoverflow.com/questions/32036146/how-to-play-a-sound-in-swift) –

+1

可能的重複[什麼是「致命的錯誤:意外地發現零,而展開一個可選值「的意思?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valued ) –

回答

2

你應該檢查一下你的音樂文件是否附在你的目標上? -

enter image description here

let path = Bundle.main.path(forResource: "Kalimba", ofType: "wav") 
    if path != nil { 
     let url = URL(fileURLWithPath: path!) 
     print(url) 
     let player = AVPlayer(url: url) 
     let playerLayer = AVPlayerLayer(player: player) 
     playerLayer.frame = self.view.bounds 
     self.view.layer.addSublayer(playerLayer) 
     player.play() 
    } else { 
     print("File Not exist") 
    } 
+0

我如何去附加目標? – Jackson1442

+0

從xcode navigator區域(xcode左側)中選擇您的音樂文件,然後從inspector(xcode右側)中選擇您的音樂文件,然後在目標成員身份上勾選上面的屏幕。 – Jack

+0

完美,謝謝!最後讓它工作,我的問題是目標附件。 – Jackson1442

相關問題