Search code examples
iosswiftavfoundationavaudioplayer

Swift 2 - AVAudioPlayer not playing audio


I'm trying to play a sound with an AVAudioPlayer, but it doesn't play. I tried both a device (iPhone 6s) and the simulator. I'm not getting any errors and it logs it played. When I set a breakpoint before audioPlayer.play() and step over it plays for a few seconds and stops then. My code:

let soundURL = NSBundle.mainBundle().URLForResource("test", withExtension: "mp3")
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
            if let soundURL = soundURL {
                let audioPlayer = try AVAudioPlayer(contentsOfURL: soundURL)
                audioPlayer.volume = 1
                audioPlayer.delegate = self
                audioPlayer.prepareToPlay()
                print(audioPlayer.duration)
                audioPlayer.play()
                print("PLAYED")
            }
        }catch {
            print("Error getting the audio file")
        }

Solution

  • Here is an example that will work. I am not sure where, in relation to the rest of your code, you have the code that you've shown above. Make sure your device volume is not on silent and is turned up...

     //declare these as instance variables
    var AudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("FileName", ofType: "mp3")!)
    var AudioPlayer = AVAudioPlayer()
    
    //inside viewDidLoad establish your AVAudioSession and configure the AudioPlayer with the contents of URL
    override func viewDidLoad() {
       super.viewDidLoad()
    
       do {
           try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            //print("AVAudioSession Category Playback OK")
        do {
            try AVAudioSession.sharedInstance().setActive(true)
              //print("AVAudioSession is Active")
        } catch let error as NSError {
            print(error.localizedDescription)
        }
       } catch let error as NSError {
           print(error.localizedDescription)
       }
    
    
       do {
           try AudioPlayer  = AVAudioPlayer(contentsOfURL: AudioURL, fileTypeHint: nil)
       } catch {
           print("errorin do-try-catch")
       }
    }
    
      //play audio
      @IBAction func playAudio(sender: AnyObject){
          AudioPlayer.play()
      }