Luke Martin Luke Martin - 4 months ago 25
iOS Question

Swift - AVAudioPlayer still playing sound when device is on silent?

I am making a fairly basic app and have been exploring the use of AVAudioPlayer to play sound in my app, but I am having an issue where it plays sound even when the device is on silent. This is the code I am using:

var audioPlayer = AVAudioPlayer()


Then in View did load:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
var beepOne = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("menu", ofType: "wav")!)
audioPlayer = AVAudioPlayer(contentsOfURL: beepOne, error: &error)
audioPlayer.prepareToPlay()


And when the sound is played:

audioPlayer.play()


What do I need to do to stop the sound from playing when the device is on Silent or switched to silent? Perhaps before
audioPlayer.play()
an if statement that detects whether the device is in silent or not?

Answer

Found what was wrong, in the second and third lines of code:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)

I had to change AVAudioSessionCategoryPlayback to AVAudioSessionCategoryAmbient

Hope this helps others who might be having the same problem :)