2014-11-22 55 views
3

隨機音頻文件我不斷收到以下錯誤,當我使用「搖晃手勢」在iPhone模擬器:播放使用雨燕

Fatal error: unexpectedly found nil while unwrapping an Optional value

這裏是我的相關代碼:

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 

    var soundFiles = ["kidLaughing", "pewpew", "pingas", "runningfeet"] 
    var player: AVAudioPlayer = AVAudioPlayer() 

    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) { 
     if event.subtype == .MotionShake { 
      var randomSoundFile = Int(arc4random_uniform(UInt32(soundFiles.count))) 
      var fileLocation = NSString(string:NSBundle.mainBundle().pathForResource("sounds/" + soundFiles[randomSoundFile], ofType: "mp3")!) 

      var error: NSError? = nil 

      player = AVAudioPlayer(contentsOfURL: NSURL(string: fileLocation), error: &error) 

      player.play() 
     } 
    } 
} 

我有一個名爲sounds的文件夾,其中有4個mp3文件。該錯誤是發生在這行代碼:

var fileLocation = NSString(string:NSBundle.mainBundle().pathForResource("sounds/" + soundFiles[randomSoundFile], ofType: "mp3")!) 

我已經試過所有我能想到的來得到這個工作,但沒有我曾嘗試工作過。任何幫助表示讚賞!

回答

2

這意味着有一個值爲零,當你斷言它不是。分開崩潰行成其組成部分,並找出到底什麼是零:

var soundFile = soundFiles[randomSoundFile] 
var path = "sounds/" + soundFile 
var fullPath = NSBundle.mainBundle().pathForResource(path, ofType: "mp3")! 
var fileLocation = NSString(string:fullPath) // fyi, this line is pointless, fullPath is already a string 

我猜想,這是在pathForResource線崩潰,因爲該文件實際上不能被發現。確保你實際上將'聲音'目錄鏈接到你的包中。

0
let path = NSBundle.mainBundle().pathForResource("Ring", ofType: "mp3") 
    let fileURL = NSURL(fileURLWithPath: path!) 
    play = AVAudioPlayer(contentsOfURL: fileURL, error: nil) 
    play.prepareToPlay() 
    play.delegate = self 
    play.play() 

這僅僅是一個例子

0

我有同樣的問題。

我在將帶有聲音文件的文件夾複製到項目中時,通過選擇「創建文件夾引用」而不是「創建組」來解決此問題。

希望這也適用於你。我對Swift和整個iOS編程都很陌生,所以我不知道幕後發生了什麼。

0

我有同樣的問題。我所做的只是「添加文件到MyProject ...」並添加完整的聲音文件夾。一旦Swift引用了該文件夾,就不需要在pathForResource參數中包含該文件夾。

1

//你也可以試試這個隨機聲音播放。

import UIKit 
import AVFoundation 
class GameScene: SKScene { 
var pinballVoiceArray = ["BS_PinballBounce1.mp3", "BS_PinballBounce2.mp3", "BS_PinballBounce3.mp3"] 
var randomIndex = 0 
override func didMoveToView(view: SKView) { 
    //use the random sound function 
    playPinballSound() 
    } 
func playPinballSound() { 
    randomIndex = Int(arc4random_uniform(UInt32(pinballVoiceArray.count))) 
    var selectedFileName = pinballVoiceArray[randomIndex] 
    runAction(SKAction.playSoundFileNamed(selectedFileName, waitForCompletion: false)) 
    } 
} 

//調用函數playPinballSound您想播放隨機聲音的位置。

+2

完美!謝謝! – Jeff 2016-11-13 21:35:41

+1

你永遠歡迎 – Rex 2017-02-07 08:20:39