8
votes

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?

2

2 Answers

18
votes

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 :)

1
votes

I'd like to add a solution using swift 2.0 which requires try/catch error handling. There's a great article on this here.

    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryAmbient, withOptions: .DuckOthers)
    } catch {
        print("AVAudioSession cannot be set")
    }       

This post was to silence audio playback if the phone is muted. I wanted to do the opposite and indeed if you replace AVAudioSessionCategoryAmbient above with AVAudioSessionCategoryPlayback, your audio will play even if the phone is muted.