How Do I Get Audio Controls on Lock Screen/Control Center from AVAudioPlayer in Swift

24,059

Solution 1

You need to invoke beginReceivingRemoteControlEvents() otherwise it will not work on the actual device.

Swift 3.1

UIApplication.shared.beginReceivingRemoteControlEvents()

If you would like to specify custom actions for the MPRemoteCommandCenter:

let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.nextTrackCommand.addTarget(self, action:#selector(nextTrackCommandSelector))

edit/update:

Apple has a sample project showing how to Becoming a Now Playable App

Solution 2

To implement this functionality, use the Media Player framework’s MPRemoteCommandCenter and MPNowPlayingInfoCenter classes with AVPlayer.

import MediaPlayer
import AVFoundation

// Configure AVPlayer
var player = AVPlayer()

Configure the Remote Command Handlers

Defines a variety of commands in the form of MPRemoteCommand objects to which you can attach custom event handlers to control playback in your app.

    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
    }
}

Provide Display Metadata

Provide a dictionary of metadata using the keys defined by MPMediaItem and MPNowPlayingInfoCenter and set that dictionary on the default instance of MPNowPlayingInfoCenter.

func setupNowPlaying() {
    // Define Now Playing Info
    var nowPlayingInfo = [String : Any]()
    nowPlayingInfo[MPMediaItemPropertyTitle] = "My Movie"

    if let image = UIImage(named: "lockscreen") {
        nowPlayingInfo[MPMediaItemPropertyArtwork] =
            MPMediaItemArtwork(boundsSize: image.size) { size in
                return image
        }
    }
    nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = playerItem.currentTime().seconds
    nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = playerItem.asset.duration.seconds
    nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate

    // Set the metadata
    MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}

For more information refer Apples official Documentation

Solution 3

func myplayer(file:String, type:String){
let path = NSBundle.mainBundle().pathForResource(file, ofType: type)!
let url = NSURL(fileURLWithPath: path)
let audioShouldPlay = audioPlaying()
do{
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    try AVAudioSession.sharedInstance().setActive(true)
    let audioPlayer:AVAudioPlayer = try AVAudioPlayer(contentsOfURL: url)
    audioPlayer.volume = slider.value
    audioPlayer.numberOfLoops = -1
    audioPlayer.prepareToPlay()
    if(audioShouldPlay){
        audioPlayer.play()
//                let mpic = MPNowPlayingInfoCenter.defaultCenter()
//                mpic.nowPlayingInfo = [MPMediaItemPropertyTitle:"title", 
MPMediaItemPropertyArtist:"artist"]
        }
    }
    catch{}
}

Solution 4

I Have this problem. You need only

audioSession.setCategory(.playback, mode: .default) or 
audioSession.setCategory(.playback, mode: .default, options: 
                                               .init(rawValue: 0)) 

Solution 5

There are already audio controls on the lock screen (the "remote control" interface). If you want them to control your app's audio, you need to make your app the remote control target, as described in Apple's documentation.

Share:
24,059

Related videos on Youtube

nbpeth
Author by

nbpeth

Updated on August 14, 2020

Comments

  • nbpeth
    nbpeth over 3 years

    New to iOS development, so here goes. I have an app that is playing audio - I'm using AVAudioPlayer to load single files by name in the app's assets. I don't want to query the user's library, only the files provided. Works great, but, I want the user to be able to pause and adjust volume from the lock screen.

    func initAudioPlayer(file:String, type:String){
        let path = NSBundle.mainBundle().pathForResource(file, ofType: type)!
        let url = NSURL(fileURLWithPath: path)
        let audioShouldPlay = audioPlaying()
        do{
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
            let audioPlayer:AVAudioPlayer = try AVAudioPlayer(contentsOfURL: url)
            audioPlayer.volume = slider.value
            audioPlayer.numberOfLoops = -1
            audioPlayer.prepareToPlay()
            if(audioShouldPlay){
                audioPlayer.play()
    //                let mpic = MPNowPlayingInfoCenter.defaultCenter()
    //                mpic.nowPlayingInfo = [MPMediaItemPropertyTitle:"title", MPMediaItemPropertyArtist:"artist"]
            }
        }
        catch{}
    }
    

    My use of AVAudioSession and MPNowPlayingInfoCenter were just experiments from reading other related posts.

    Background mode is enabled for audio in my app's plist file

    • matt
      matt over 8 years
      What's the question / problem?
    • nbpeth
      nbpeth over 8 years
      The question is how I get audio controls to the lock screen. I've seen that the MPNowPlayingInfoCenter nowPlayingInfo is how one passes song meta data to the lock screen / control center, but I'm missing on how to tie it in with AVAudioPlayer
    • matt
      matt over 8 years
      There are already audio controls on the lock screen.
    • nbpeth
      nbpeth over 8 years
      No controls appear for the audio playing for my app
    • nbpeth
      nbpeth over 8 years
      However, I have required background modes set to 'app plays audio or streams audio..'. Something interesting is that audio plays in the background when using the simulators in xcode, but when I deploy the app to an actual device it doesn't work. maybe there's something missing in the background mode configuration, but I can't seem to find anything outside of adding that property to info.plist
    • matt
      matt over 8 years
      This has nothing, per se, to do with background mode. If you are remote control target, that keeps working if you are also playing in the background, but playing in the background does not magically make you the remote control target.
  • matt
    matt over 8 years
    I explain one way to do this in my book; example code here: github.com/mattneub/Programming-iOS-Book-Examples/blob/maste‌​r/… Or you can use MPRemoteCommandCenter.
  • nbpeth
    nbpeth over 8 years
    haha, alright. I was actually looking at this earlier. I'll explore the remote control end of it. Any thoughts on why background mode might be working in simulator but not on an actual iphone
  • matt
    matt over 8 years
    Simulator is unreliable with regard to background modes - do not use it for any kind of experimentation in that regard. This is a known, acknowledged bug.
  • nbpeth
    nbpeth over 8 years
    final answer, UIApplication.sharedApplication().beginReceivingRemoteContro‌​lEvents() and AVAudioSession.sharedInstance().setCategory(AVAudioSessionCa‌​tegoryPlayback)
  • MikeG
    MikeG about 7 years
    where exactly should these lines be placed? I am unable to get any lock screen controls to display for my app although audio playback works fine
  • Nurbol
    Nurbol almost 7 years
    Link above is broke unfortunately
  • Surjeet Rajput
    Surjeet Rajput almost 7 years
    @mike in didFinishLaunchOptions of appdelege. Its Late but this link is useful developer.apple.com/library/content/samplecode/…
  • kikeenrique
    kikeenrique over 5 years
    according to Readme in sample code provided by @commando24, "When using MPRemoteCommandCenter you do not need to call UIApplication.beginReceivingRemoteControlEvents()."
  • Jakub Truhlář
    Jakub Truhlář over 5 years
    In iOS 7.1 and later, use the shared MPRemoteCommandCenter object to register for remote control events. You do not need to call beginReceivingRemoteControlEvents method when using the shared command center object.
  • Sasho
    Sasho almost 5 years
    + for the mpic.nowPlayingInfo
  • medyas
    medyas over 4 years
    hey, i am having the same problem and no luck solving it stackoverflow.com/questions/59886747/…
  • Dinu Nicolae
    Dinu Nicolae over 3 years
    can I see this in a simulator?
  • Sreekuttan
    Sreekuttan over 3 years
    The simulator doesn't have the audio control options in lock screen.!
  • Rufus Mall
    Rufus Mall almost 3 years
    This sorted it for me!