简体   繁体   中英

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...

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.

this piece of code worked for me fine

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

and you have to define audioPlayer as a class member or it goes out of scope otherwise and it won't work.

var audioPlayer: AVAudioPlayer!

thats it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM