2015-09-22 36 views
3

您好我正嘗試在swift 2中播放帶有以下代碼的音樂文件。基本上我只是用名字f.mp3到asses文件夾,並且我的代碼中斷了以下消息: 意外地發現零,同時展開可選值。在哪裏我需要把我的MP3文件,所以IOS可以找到它。謝謝致命錯誤:在Swift 2中使用AudioPlayer時解開可選值時出現意外的零錯誤

var audioPlayer: AVAudioPlayer! = nil 
func playMyFile() { 

    let path = NSBundle.mainBundle().pathForResource("f", ofType: "mp3") 
    let fileURL = NSURL(fileURLWithPath: path) 

    do { 
    try audioPlayer = AVAudioPlayer(contentsOfURL: fileURL) 
    } catch { 
     print("error") 
    } 
    audioPlayer.prepareToPlay() 
    audioPlayer.delegate = self 
    audioPlayer.play() 

} 
+0

可能重複(http://stackoverflow.com/questions/32170456/what-does- fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – jtbandes

回答

10

您的代碼工作正常與我的項目,這裏是我的完整代碼:

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 

    var audioPlayer: AVAudioPlayer! = nil 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     playMyFile() 
    } 

    func playMyFile() { 

     let path = NSBundle.mainBundle().pathForResource("f", ofType: "mp3") 
     let fileURL = NSURL(fileURLWithPath: path!) 

     do { 
      try audioPlayer = AVAudioPlayer(contentsOfURL: fileURL) 
     } catch { 
      print("error") 
     } 
     audioPlayer.prepareToPlay() 
     audioPlayer.play() 
    } 
} 

確保您的聲音加入到複製包資源是這樣的:

enter image description here

如果沒有添加,則用這種方式添加:

enter image description here

檢查THIS sample for more Info。在斯威夫特3

使用AudioPlayer時,我已經使用這個代碼播放聲音選擇collectionViewCell:(路徑withPath!) - :

+0

非常感謝你!順便說一句,我不得不重新命名一個文件,因爲它告訴我,我不能添加它,因爲具有這樣的名稱的文件已經存在。 – user5309974

+0

打開項目文件夾並先刪除舊文件..再次添加新文件.. :) –

+0

高興地幫助你.. :) –

0

致命錯誤,意外地發現零而展開的可選值讓URL = NSURL.fileURL -----

func playSound() 
{ 
    do 
    { 
     let audioPath = Bundle.main.path(forResource: sounds[indexPath.row], ofType: ".mp3") 
     try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL) 
    } 
    catch 
    { 
     print("ERROR") 
    } 

    audioPlayer.prepareToPlay() 

    audioPlayer.play() 
} 
的[什麼是「致命的錯誤:零而展開的可選值意外地發現」?意思]
相關問題