2014-11-22 143 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