声音在模拟器上播放,但不在iPhone上播放



我正在做一个教程,我测试了这段代码,当我在模拟器上运行时它可以工作,但当我在 iPhone 上测试时它不能。 我调试了,他没有犯错,只是不播放声音。

import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var audioPlayer = AVAudioPlayer()
@IBAction func notePressed(_ sender: UIButton) {
playSound(tag: sender.tag)
}
func playSound(tag: Int) {
let soundURL = Bundle.main.url(forResource: "note(tag)", withExtension: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
} catch {
print(error)
}
audioPlayer.numberOfLoops = -1
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}

播放音频之前必须设置AVAudioSession.sharedInstance().setCategory(.playback)

最新更新