Search code examples
iosswiftaudioavaudioplayer

AVAudioPlayer not playing the MP3


I need to reproduce an MP3 file and I'm using this code:

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)
   }
}

I'm not getting any error, but no sound is reproduced. I've also enabled Inter-App audio in the App Capabilities, added the MP3 file in "Copy Bundle Resources" and I'm testing on a real device. Any suggestion? I've tried all the other solutions provided in other questions of this type...


Solution

  • I've solved.

    Everything was not working just because I was reproducing this code in a background queue. Moving it to the main queue just solved the problem.