Reputation: 1021
To enable background music from app Spotify or Music app, I use this code:
do
{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
try AVAudioSession.sharedInstance().setActive(true)
}
catch let error as NSError
{
print(error)
}
But how can i reverse that, to stop allow background music playing?
Upvotes: 4
Views: 2197
Reputation: 4604
private func setIsAudioPlaysInBackground(isPlay: Bool) {
if isPlay {
try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.ambient)
} else {
try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
}
try? AVAudioSession.sharedInstance().setActive(true)
}
Upvotes: 0
Reputation: 535999
According to the documentation, the chief playback audio session categories are:
AVAudioSessionCategoryAmbient
When you use this category, audio from other apps mixes with your audio.
AVAudioSessionCategorySoloAmbient
By default, using this category implies that your app’s audio is nonmixable—activating your session will interrupt any other audio sessions which are also nonmixable.
AVAudioSessionCategoryPlayback
By default, using this category implies that your app’s audio is nonmixable—activating your session will interrupt any other audio sessions which are also nonmixable.
So, you've deliberately picked the only playback category which doesn't silence nonmixable background audio. If you do want to silence nonmixable background audio, pick one of the other categories. There's nothing wrong with changing categories at any time.
Upvotes: 4
Reputation: 83
Have you tried this code?
AVAudioSession.sharedInstance().setActive(false)
I haven't tested it but from what I assume it would stop the music.
Upvotes: -1