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

Sound plays on emulator but not on 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)