1

I am trying to find a way to pause any playing media on the device, so I was thinking of triggering the same logic that is fired when a user press the headphone "middle button"

I managed to prevent music from resuming (after I pause it within my app, which basically start an AVAudioSession for recording) by NOT setting the AVAudioSession active property to false and leave it hanging, but I am pretty sure thats a bad way to do it. If I deactivate it the music resumes. The other option I am thinking of is playing some kind of silent loop that would "imitate" the silence I need to do. But I think if what I am seeking is doable, it would be the best approach as I understood from this question it cannot be done using the normal means

func stopAudioSession() {
let audioSession = AVAudioSession.sharedInstance(
  do {
       if audioSession.secondaryAudioShouldBeSilencedHint{
            print("someone is playing....")
       }
   try audioSession.setActive(false, options: .notifyOthersOnDeactivation)
        isSessionActive = false
        } catch let error as NSError {
        print("Unable to deactivate audio session: \(error.localizedDescription)")
       print("retying.......")            
        }
    }

In this code snippet as the function name implies I set active to false, tried to find other options but I could not find another way of stopping my recording session and prevent resume of the other app that was already playing

If someone can guide me to which library I should look into, if for example I can tap into the H/W part and trigger it OR if I can find out which library is listening to this button press event and handling the pause/play functionality

Sherbieny
  • 117
  • 3
  • 17

1 Answers1

0

A friend of mine who is more experienced in IOS development suggested the following workaround and it worked - I am posting it here as it might help someone trying to achieve a similar behaviour.

In order to stop/pause what is currently being played on a user device, you will need to add a music player into your app. then at the point where you need to pause/stop the current media, you just initiate the player, play and then pause/stop it - simple :)

like so:

let musicPlayer = MPMusicPlayerApplicationController.applicationQueuePlayer

   func stopMedia(){

    MPMediaLibrary.requestAuthorization({(newPermissionStatus: MPMediaLibraryAuthorizationStatus) in
        self.musicPlayer.setQueue(with: .songs())
        self.musicPlayer.play()
        print("Stopping music player")
        self.musicPlayer.pause()
        print("Stopped music player")
    })

}

the part with MPMediaLibrary.requestAuthorization is needed to avoid an authorisation error when accessing user's media library. and of course you will need to add the Privacy - Media Library Usage Description key into your Info.plist file

Sherbieny
  • 117
  • 3
  • 17