2016-05-31 85 views
0

我想打在我的項目的音頻在做IOS(SWIFT語言)。我不能播放音頻因錯誤如何解決線程1:EXC_BAD_INSTRUCTION(代碼= EXC_I386_INVOP,子碼=爲0x0)

線程1:EXC_BAD_INSTRUCTION(代碼= EXC_I386_INVOP,子碼=爲0x0)

我能起到同樣的音頻時不將其分離。但是,當我將它添加到我的項目獲取上述錯誤。我嘗試用不同的代碼播放音頻。但同樣的錯誤在同一行中重複出現。

@IBAction func playaudio(sender:AnyObject) 
    { 
    var ButtonAudioPlayer: AVAudioplayer! 
    let path = NSBundle.mainBundle()pathResource("ButtonAudio.wav",ofType:nil)! // error 
    let url = NSURL(fileURLWithPath: path) 
    do 
    { 
     let ButtonAudioPlayer1 = try! AVAudioPlayer(contesOfURL:url) 
     ButtonAudioPlayer = ButtonAudioPlayer1 
     ButtonAudioPlayer1.play() 
    } 
} 

回答

2

你得到EXC_BAD_INSTRUCTION 到期強行展開一個零路徑。檢查文件的路徑並使用ofType中的「wav」。這樣的代碼將幫助你解決這個問題:

guard let path = NSBundle.mainBundle().pathForResource("ButtonAudio", ofType: "wav") else { 
    print("there is not such a file") 
    return 
} 
+0

我試過這種方式。但我仍然在同一行中得到同樣的錯誤。 – sitara

+0

嘗試使用'URLForResource(_:withExtension :)'並讓我知道它是否會改變任何東西。 https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/#//apple_ref/occ/instm/NSBundle/URLForResource:withExtension: –

+0

始終打印「沒有這樣的文件「 – sitara

1

在這裏我注意到了一些其他項目。因爲它缺少

你的路徑上分配不正確。在pathForResource之前。如上所述,你也錯過了這種類型。

當分配buttonAudioPlayer,你有一個錯字,你缺少的contentsOfUrl n個。

您還沒有使用駝峯你的變量,這是使用常見的做法。

@IBAction func playAudio(sender:AnyObject) { 
    var buttonAudioPlayer: AVAudioPlayer 
    if let path = NSBundle.mainBundle().pathForResource("ButtonAudio", ofType: "wav") { 
     let url = NSURL(fileURLWithPath: path) 
     do { 
      let buttonAudioPlayer1 = try! AVAudioPlayer(contentsOfURL: url) 
      buttonAudioPlayer = buttonAudioPlayer1 
      buttonAudioPlayer.play() 
     } 
    } 
} 
0

嘗試這樣,

// Grab the path, make sure to add it to your project! 
var path = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ButtonAudio", ofType: "wav")) 
var audioPlayer = AVAudioPlayer() 

audioPlayer = AVAudioPlayer(contentsOfURL: path, error: nil) 
audioPlayer.prepareToPlay() 

audioPlayer.play() 

,並確保您已在主束添加音頻正常。打印它是你得到的路徑。

相關問題