0

I'm sure I'm asking a simple question but I've only just started coding... so take pity on me! I'm on Xcode 7 Swift 2. The music player is of type AVAudioPlayer.If I launch the app and move the volume slider(type UISlider) before pressing the play button it crashes the app, while after I press play it works perfectly, even when the music is paused. I know the reason is because of "musicPlayer.playing" in the volumeSlider func. I tried many If statements (Eg."if musicPaused etc..) but I couldn't get it to work. Thank you for your help. This is the volume slider func:

@IBAction func volumeSliderChanged(sender: AnyObject) {
    musicPlayer.playing
    musicPlayer.volume = volumeSlider.value
}

This is the Play func:

 @IBAction  func playPause(sender: AnyObject) {
    var items = toolbar.items!

    if musicPaused == false {
        playPauseBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "playPause:")
        items[0] = playPauseBtn
        toolbar.setItems(items, animated: true)
        musicPlayer.play()
        musicPaused = true
    }
    else{
        var items = toolbar.items!
        playPauseBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "playPause:")
        items[0] = playPauseBtn
        toolbar.setItems(items, animated: true)
        musicPlayer.pause()
        musicPaused = false
    }
}

@IBAction func playPauseButton(sender: UIButton) {
    let playBtn = sender as UIButton
    if toggleState == 1 {

        if isPlaying {
            musicPlayer.play()

        }else{

            playMusic()
        }

        toggleState = 2
        playBtn.setImage(UIImage(named:"100_pause.png"),forState:UIControlState.Normal)

    } else {

        musicPlayer.pause()
        toggleState = 1
        playBtn.setImage(UIImage(named:"100_play-arrow.png"),forState:UIControlState.Normal)
    }
}

This is my musicPlayer declaration:

var musicPlayer: AVAudioPlayer = AVAudioPlayer()
Marie
  • 3
  • 2

1 Answers1

0

It would help if you included the code where 'musicPlayer' was declared. What did the error log say after the crash?

I would recommend using the MPVolumeView class to control your audio. It should control the device volume which is what I think you are looking for. I've attached someone else's post with a similar issue. Source: How to change ios volume in swift with help UISlider

Community
  • 1
  • 1
  • Hi, thank you for the reply. I edited the post and added the declaration. The error shows the line "musicPlayer.playing", Thread 1: EXC_BAD_ACCESS (code=1, address=0x38) – Marie Dec 01 '15 at 09:30