iosswiftxcodeavaudiosessionaudiosession

How to stop (or pause) the device's audio in Swift?


I am making a music timer which will stop music (playing from Spotify, Apple Music, etc.) after an entered time. Is there a way to stop that audio session or pause the audio which is being played from another app from my app?

Since I don't have a local audio player in my app, I cannot just simply stop the player (as you usually would when playing audio from your app).

Any help is appreciated!


Solution

    1. Import AVFoundation in the file which will stop the audio.

    2. Add this code once the timer is done:

      do {
          try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
          try AVAudioSession.sharedInstance().setActive(true)
      } catch { print(error.localizedDescription) }