我试图在应用启动后进行音乐循环播放。没有显示构建错误,但音乐无法播放。这是我在viewDidLoad中的代码。我还在顶部导入了AVFoundation和SpriteKit。 (在类似问题中提出的解决方案与Swift 2相关,在Swift 3中不起作用)
override func viewDidLoad() {
//这里我改变了datepicker的背景颜色
dateWheel.backgroundColor = .blue
dateWheel.setValue(UIColor.white, forKeyPath: "textColor")
//应用程序启动后音乐应该开始播放
func playSound(soundName: String)
{
let musicPlay = NSURL(fileURLWithPath: Bundle.main.path(forResource: "chinaAudioNew", ofType: "mp3")!)
do{
let audioPlayer = try AVAudioPlayer(contentsOf:musicPlay as URL)
audioPlayer.prepareToPlay()
audioPlayer.play()
audioPlayer.numberOfLoops = -1
}catch {
print("Error getting the audio file")
}
}
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:1)
这是你的问题:
let audioPlayer = try AVAudioPlayer(contentsOf:musicPlay as URL)
这是一个本地变量,所以它甚至在有机会开始播放之前就已经不存在了。