2016-08-09 52 views
1

此程序之前工作,我不相信我改变了任何东西。这是代码。我得到了抛出的错误:文件未找到:bgMusicAVAudioPlayer不工作了

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

回答

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

然后加载URL到AVAudioPlayer。

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

+0

“可选类型的值'字符串?'不打开;你的意思是使用'!'要么 '?'?”这是在第二行 –

+0

通过添加'!'解包可选项路径后。如果你添加了文件,假设你的文件在那里应该是安全的。如果它崩溃,那么你的文件可能不在正确的项目或文件名是错误的。 –