iosswiftbackground-music

swift start music after user phone call


I am not quite sure if I am missing a function or something, but when a users phone rings and or they ask siri or anything that stops my app audio from playing. It does not re-start my app playing when the user has finished their task.

I am wondering is there a function I am missing, or can Apple iOS apps not do this?

I thought it would be something to do with:

func setupRemoteTransportControls() {
   // Get the shared MPRemoteCommandCenter
    let commandCenter = MPRemoteCommandCenter.shared()

    // Add handler for Play Command
    commandCenter.playCommand.addTarget { [unowned self] event in
        if self.player?.rate == 0.0 {
            self.player?.play()
            return .success
        }
        return .commandFailed
    }

    // Add handler for Pause Command
    commandCenter.pauseCommand.addTarget { [unowned self] event in
        if self.player?.rate == 1.0 {
            self.player?.pause()
            return .success
        }
        return .commandFailed
    }

   // self.nowplaying(artist: "Anna", song: "test")


}

I have found that I need to add this part but how do I call it?

func handleInterruption(notification: Notification) {

        guard let userInfo = notification.userInfo,
            let interruptionTypeRawValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
            let interruptionType = AVAudioSession.InterruptionType(rawValue: interruptionTypeRawValue) else {
            return
        }

        switch interruptionType {
        case .began:
            print("interruption began")
        case .ended:
            print("interruption ended")
        default:
            print("UNKNOWN")
        }

    }

Solution

  • You need to set your audio session to AVAudioSessionCategoryPlayback. If you don't set this mode, you will have the default mode AVAudioSessionCategorySoloAmbient.

    You can set the mode in didFinishLaunching.

    e.g.

    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        // Get the singleton instance.
        let audioSession = AVAudioSession.sharedInstance()
        do {
            // Set the audio session category, mode, and options.
            try audioSession.setCategory(.playback, mode: .default, options: [])
        } catch {
            print("Failed to set audio session category.")
        }
        
        // Other post-launch configuration.
        return true
    }
    

    You will also need to implement interruption observation

    func setupNotifications() {
        // Get the default notification center instance.
        let nc = NotificationCenter.default
        nc.addObserver(self,
                       selector: #selector(handleInterruption),
                       name: AVAudioSession.interruptionNotification,
                       object: nil)
    }
    
    @objc func handleInterruption(notification: Notification) {
        // To be implemented.
    }