Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Stop avaudioplayer

I am trying to build a soundboard into an app and have figured out an efficient way of using tags to control playing the sounds. However I am now trying to integrate a pause button that can be used with the .stop() method on the AVAudioPlayer however I get an error with my current code:

EXC_BAD_ACCESS

This is what I am using at the moment, any ideas?

import UIKit
import AVFoundation

let soundFilenames = ["sound","sound2","sound3"]
var audioPlayers = [AVAudioPlayer]()

class SecondViewController: UIViewController {

     var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

     for sound in soundFilenames {
          do {
               let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: "mp3")!)
               let audioPlayer = try AVAudioPlayer(contentsOfURL: url)
               audioPlayers.append(audioPlayer)
          } catch {
               //Catch error thrown
               audioPlayers.append(AVAudioPlayer())
          }
     }
     }


     @IBAction func buttonPressed(sender: UIButton) {
          let audioPlayer = audioPlayers[sender.tag]
          audioPlayer.play()
     }
     @IBAction func stop(sender: UIButton) {
          audioPlayer.stop()
     }

}
like image 942
dwinnbrown Avatar asked Mar 11 '23 16:03

dwinnbrown


1 Answers

Your audioPlayer in stop function is not the playing player. You should assign it in buttonPressed function.

@IBAction func buttonPressed(sender: UIButton) {
      audioPlayer = audioPlayers[sender.tag]
      audioPlayer.play()
 }

By the way, You can mark audioPlayer as a "?" property, it will be more efficient when init this Controller.

class SecondViewController: UIViewController {

     var audioPlayer: AVAudioPlayer?

     let enableMuiltPlayers = false
....


    @IBAction func buttonPressed(sender: UIButton) {
          if sender.tag < audioPlayers.count else {
               print("out of range")
               return
          }
          if enableMuiltPlayers {
             audioPlayers[sender.tag].play()
          } else {
             audioPlayer?.stop()
             //set the current playing player
             audioPlayer = audioPlayers[sender.tag]
             audioPlayer?.play()
          }
     }

     @IBAction func stop(sender: UIButton) {
          let wantToStopAll = false
          if enableMuiltPlayers  && wantToStopAll {
              stopAll()
          } else {
              audioPlayer?.stop()
          }
          audioPlayer = nil
     }
}

to stop all:

fun stopAll() {
    for player in audioPlayers {
        player.stop()
    }
}
like image 71
Hao Avatar answered Mar 15 '23 04:03

Hao