Realization of Music Lock Screen and Backstage Playing

Keywords: Session MediaPlayer iOS

Preface

After playing music by oneself, one can operate the lock screen and play back-stage, mainly using AVAudioSession class. This class is a singleton class that sets some context of APP about Audio and passes some of its behavior to the system.

An audio session is a singleton object that you employ to set the audio context for your app and to express to the system your intentions for your app's audio behavior.

This is Apple's official document for AudioSession.

Setting Background Play Function


Open Target - > Background Modes and click Audio 1.

Set in the code to activate the audio settings

First, you need to activate remote control in AppDeleage

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
    return YES;
}

Return canBecomeFirstResponder to YES, which defaults to NO

- (BOOL)canBecomeFirstResponder {
    return YES;
}

Then set the AVAuido Session Category policy in the code

 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];

You need to set up the Category of AVAudio Session, which is a string. Then call the setActive function to activate the audio settings

Type of reply Explain Do you require input? Is output required? Do you follow the mute key?
AVAudioSessionCategoryAmbient Mix playback, which can be played at the same time as other audio applications no yes yes
AVAudioSessionCategorySoloAmbient Exclusive play no yes yes
AVAudioSessionCategoryPlayback Backstage play, exclusive no yes no
AVAudioSessionCategoryRecord Recording mode yes no no
AVAudioSessionCategoryPlayAndRecord Play and record, which can be recorded or played at this time yes yes no
AVAudioSessionCategoryAudioProcessing Hardware decodes audio, which cannot be played or recorded at this time no no no
AVAudioSessionCategoryMultiRoute Multiple inputs and outputs, such as simultaneous playback of headphones and USB devices yes yes no

With this setup, when the App background runs, you can continue to play songs.

Lock screen and shortcut bar display audio and video information

If you want to control music and display information of playing music on the control bar, you need to introduce

#import <MediaPlayer/MPNowPlayingInfoCenter.h>
#import <MediaPlayer/MPMediaItem.h>

MPNowPlayingInfoCenter provides an interface for setting the current now playing information for the application. This information will be displayed wherever now playing information typically appears, such as the lock screen and app switcher. The now playing info dictionary contains a group of metadata properties for a now playing item. The list of property constants is available in <MediaPlayer/MPMediaItem.h> The properties which are currently supported include:
MPMediaItemPropertyAlbumTitle
MPMediaItemPropertyAlbumTrackCount
MPMediaItemPropertyAlbumTrackNumber
MPMediaItemPropertyArtist
MPMediaItemPropertyArtwork
MPMediaItemPropertyComposer
MPMediaItemPropertyDiscCount
MPMediaItemPropertyDiscNumber
MPMediaItemPropertyGenre
MPMediaItemPropertyPersistentID
MPMediaItemPropertyPlaybackDuration
MPMediaItemPropertyTitle

In addition, metadata properties specific to the current playback session may also be specified – see "Additional metadata properties" below.

The MPNowPlaying InfoCenter class provides information to set the current audio and video playing. This information will be displayed in specific places, such as lock screens and APP switching. The information played is stored as a metadata in a dictionary. These stored properties contain the above entries.
MPMediaItemProperty Artwork is a class used to display pictures and lyrics of songs.

MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"cyx.jpg"]];
@property (copy, nullable) NSDictionary<NSString *, id> *nowPlayingInfo;

So you can set up the dictionary according to what you want to display. For example, to show the singer, the name of the song, and the time of the song

[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:@{MPMediaItemPropertyArtist:@"Eason Chan",MPMediaItemPropertyAlbumTitle:@"Tug-of-war",MPMediaItemPropertyPlaybackDuration:@"280"}];

Control of lock screen and shortcut bar

If you want to control music playing on lock screen and shortcut bar, you need to implement the following interface

//Response to remote music playback control messages
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        switch (receivedEvent.subtype) {
            case UIEventSubtypeRemoteControlPlay:
                [player play];
                NSLog(@"Pause playback");
                break;
            case UIEventSubtypeRemoteControlPause:
                [player pause];
                NSLog(@"Continue playing");
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                NSLog(@"Next song");
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                NSLog(@"Last song");
                break;
            default:
                break;
        }
    }
}

UIEvent is an enumeration that contains the behavior to be controlled

typedef NS_ENUM(NSInteger, UIEventSubtype) {
    // available in iPhone OS 3.0
    UIEventSubtypeNone                              = 0,

    // for UIEventTypeMotion, available in iPhone OS 3.0
    UIEventSubtypeMotionShake                       = 1,

    // for UIEventTypeRemoteControl, available in iOS 4.0
    UIEventSubtypeRemoteControlPlay                 = 100,
    UIEventSubtypeRemoteControlPause                = 101,
    UIEventSubtypeRemoteControlStop                 = 102,
    UIEventSubtypeRemoteControlTogglePlayPause      = 103,
    UIEventSubtypeRemoteControlNextTrack            = 104,
    UIEventSubtypeRemoteControlPreviousTrack        = 105,
    UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
    UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
    UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
    UIEventSubtypeRemoteControlEndSeekingForward    = 109,
};

Through specific values, different functions are invoked to control the playback of audio and video.

Posted by ksp on Sat, 01 Jun 2019 14:21:26 -0700