为简单起见,假设此视图在您单击所述按钮时在按钮中显示字母。
我一直在尝试播放与每个按钮关联的音频文件,但文件永远不会播放。单独的按钮从不给出插座,但它们都连接到Touch Up Inside上的功能。
class UIAlphabetController: UIViewController, AVAudioPlayerDelegate{
@IBAction func PlaySound(Sender: UIButton) {
let soundname:String = Sender.currentTitle!
var player: AVAudioPlayer?
let url = Bundle.main.url(forResource: soundname, withExtension: "mp3")
do {
player = try AVAudioPlayer(contentsOf: url!)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error { print(error.localizedDescription) }
}
}
由于我遇到了这个问题,AQDefaultDevice (188): skipping input stream 0 0 0x0
消息已经出现。在使用断点进行测试时,soundname
和url
都具有预期值。
有没有人知道如何解决这个问题?
答案 0 :(得分:2)
将AVAudioPlayer的实例移出方法之外。如果你这样做,它会让玩家保持足够长的时间来播放声音。它不起作用的原因是因为它在方法完成后会破坏播放器实例,因为它认为你已经完成了它的使用。
class UIAlphabetController: UIViewController, AVAudioPlayerDelegate {
var player: AVAudioPlayer?
@IBAction func PlaySound(Sender: UIButton) {
let soundname:String = Sender.currentTitle!
let url = Bundle.main.url(forResource: soundname, withExtension: "mp3")
do {
player = try AVAudioPlayer(contentsOf: url!)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error { print(error.localizedDescription) }
}
}