AVAudioPlayer 不播放 MP3

AVAudioPlayer not playing the MP3

我需要复制一个 MP3 文件,我正在使用此代码:

import AVFoundation

var player: AVAudioPlayer?

@IBAction func playSound(sender: UIButton) {

   //Making the phone vibrate
   AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))

   //Playing a sound
   let url = Bundle.main.url(forResource: "audio_file_name", withExtension: "mp3")!
   do {
      self.player = try AVAudioPlayer(contentsOf: url)
      self.player?.delegate = self
      self.player?.prepareToPlay()
      self.player?.play()
   } catch let error {
      print(error.localizedDescription)
   }
}

我没有收到任何错误,但没有声音被再现。我还在 App Capabilities 中启用了 Inter-App 音频,在 "Copy Bundle Resources" 中添加了 MP3 文件,我正在真实设备上进行测试。 有什么建议吗?我已经尝试了此类其他问题中提供的所有其他解决方案...

这段代码对我来说很好

func playAudio(){
     let audioUrl = URL(fileURLWithPath: value, relativeTo: someBasePath)
            do{
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                try AVAudioSession.sharedInstance().setActive(true)
                audioPlayer = try AVAudioPlayer(contentsOf: audioUrl, fileTypeHint: AVFileTypeMPEGLayer3)
                audioPlayer.prepareToPlay()
                audioPlayer.play()
            }catch{
                print(error.localizedDescription)
            }
}

并且您必须将 audioPlayer 定义为 class 成员,否则它会超出范围,否则它将无法工作。

var audioPlayer: AVAudioPlayer!

就是这样

我解决了

因为我在后台队列中重现此代码,所以一切都无法正常工作。 把它移到主队列就解决了这个问题。