使用Swift播放随机音频文件

时间:2014-11-22 05:22:04

标签: ios objective-c swift avaudioplayer nsbundle

当我在iPhone模拟器中使用" Shake Gesture" 时,我一直收到以下错误:

  

致命错误:在解包可选值时意外发现nil

以下是我的相关代码:

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")!)

我已经尝试了一切我能想到的东西让它发挥作用,但我尝试过的任何东西都没有用。任何帮助表示赞赏!

5 个答案:

答案 0 :(得分:2)

这意味着当你断言它不是时,有一个值是nil。将崩溃线分成它的组件,找出确切的nil:

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行崩溃,因为实际上找不到该文件。确保您实际上是在连接“声音”和“声音”。目录进入你的包。

答案 1 :(得分: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 :(得分: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()

这只是一个例子

答案 3 :(得分:0)

我遇到了同样的问题。

我通过选择"创建文件夹引用来解决它"当将包含声音文件的文件夹复制到项目时,而不是"创建组"。

希望这也适合你。我对Swift和整个iOS编程都很陌生,所以我不知道幕后到底发生了什么。

答案 4 :(得分:0)

我遇到了同样的问题。我所做的只是“将文件添加到MyProject ...”并添加整个声音文件夹。一旦Swift引用了这个文件夹,就不需要在pathForResource参数中包含该文件夹了。

相关问题