Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 721
Luke Martin Avatar asked Feb 13 '15 09:02

Luke Martin


1 Answers

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

like image 62
Luke Martin Avatar answered Oct 16 '22 17:10

Luke Martin