Audio 在viewDidLoad Swift 3中循环播放音频音乐时出现问题
我尝试在应用程序启动后让音乐循环。没有显示构建错误,但音乐不会播放。下面是我在viewDidLoad中的代码。我还在顶部导入了AVFoundation和SpriteKit。(类似问题中提出的解决方案与Swift 2相关,不适用于Swift 3) //在这里,我更改日期选择器的背景色Audio 在viewDidLoad Swift 3中循环播放音频音乐时出现问题,audio,swift3,avfoundation,avaudioplayer,Audio,Swift3,Avfoundation,Avaudioplayer,我尝试在应用程序启动后让音乐循环。没有显示构建错误,但音乐不会播放。下面是我在viewDidLoad中的代码。我还在顶部导入了AVFoundation和SpriteKit。(类似问题中提出的解决方案与Swift 2相关,不适用于Swift 3) //在这里,我更改日期选择器的背景色 dateWheel.backgroundColor = .blue dateWheel.setValue(UIColor.white, forKeyPath: "textColor") //一旦应用
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.
}
}这是你的问题:
let audioPlayer = try AVAudioPlayer(contentsOf:musicPlay as URL)
这是一个局部变量,因此它在有机会开始播放之前就不存在了。我应该在它的位置放置什么?请看,我在函数之外添加了这个,但仍然不是音频。。。var audioPlayer:AVAudioPlayer=AVAudioPlayer();我不知道你现在在做什么。我知道的是你在问题中的密码。我向你们保证,我的回答正确地解释了为什么代码永远不会播放任何声音。所以我应该放弃整个代码块或者仅仅是那一行?我如何使它成为一个属性,使它始终存在?可能的复制品是swift 3,我尝试了这些解决方案,但声音仍然没有播放
let audioPlayer = try AVAudioPlayer(contentsOf:musicPlay as URL)