dwinnbrown dwinnbrown - 4 months ago 41
iOS Question

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

}

Hao Hao
Answer

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