AVAudioPlayer不再工作了

时间:2016-08-09 18:49:13

标签: swift avaudioplayer

这个程序以前工作过,我不相信我改变了什么。这是代码。我得到抛出的错误:找不到文件:bgMusic

import SpriteKit
import AVFoundation

class GameScene: SKScene, SKPhysicsContactDelegate {

    var backgroundMusicPlayer = AVAudioPlayer()

    func playBackgroundMusic(filename: String) {
        let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
        guard let newURL = url else {
            print("Could not find file: \(filename)")
            return
        }
        do {
            backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
            backgroundMusicPlayer.numberOfLoops = -1
            backgroundMusicPlayer.prepareToPlay()
            backgroundMusicPlayer.play()
        } catch let error as NSError {
            print(error.description)
        }
    }


    override init(size: CGSize) {
        super.init(size: size)

        playBackgroundMusic("bgMusic")
}

1 个答案:

答案 0 :(得分:0)

尝试获取文件路径。这对我来说每次都适用。

//Change 'ofType' to whatever the file type is. (.m4a, .mp3, etc.)
let path = NSBundle.mainBundle().pathForResource(filename, ofType: ".mp3")
let url = NSURL.fileURLWithPath(path!)

然后将网址加载到AVAudioPlayer。

如果这不起作用,请确保文件名正确并将其添加到项目中。祝你好运!