音乐锁屏、后台播放的实现

前言

实现自己播放音乐后,可以进行锁屏操作和后台播放,主要是利用AVAudioSession类。这个类是个单例类,用来设置APP的关于Audio的一些上下文,把自己APP的一些行为传递给系统

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.

这是Apple官方文档对应AudioSession的说明。

设置后台播放的功能

这里写图片描述
开启Target->Background Modes,点选第一项 Audio。

在代码中设置,激活音频设置

首先要在AppDeleage中激活远程控制

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

返回canBecomeFirstResponder为YES,这个值默认为NO

- (BOOL)canBecomeFirstResponder {
    return YES;
}

然后在代码中设置AVAuidoSessionCategory的策略

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

需要设置一下AVAudioSession的Category,这是一个字符串。然后调用setActive函数来激活音频设置

回话类型说明是否要求输入是否要求输出是否遵从静音键
AVAudioSessionCategoryAmbient混音播放,可以与其他音频应用同时播放
AVAudioSessionCategorySoloAmbient独占播放
AVAudioSessionCategoryPlayback后台播放,独占
AVAudioSessionCategoryRecord录音模式
AVAudioSessionCategoryPlayAndRecord播放和录音,此时可以录音也可以播放
AVAudioSessionCategoryAudioProcessing硬件解码音频,此时不能播放和录制
AVAudioSessionCategoryMultiRoute多种输入输出,例如可以耳机、USB设备同时播放

通过这样设置以后,当App后台运行的时候,就可以继续放歌了。

锁屏 和快捷栏显示音视频信息

如果要在控制栏上控制音乐和显示播放音乐的信息,需要引入

#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.

MPNowPlayingInfoCenter类提供了一个设置当前播放的音视频的信息。这个信息将被显示在特定的地方,例如锁屏和APP切换。播放的东东的信息被作为一个元数据存储在一个dictionary里面。这些被存储的属性包含以上几个条目。
其中MPMediaItemPropertyArtwork是一个类,用来显示歌曲图片和歌词

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

所以可以根据要显示的的内容,设置这个字典。例如要显示歌手、歌曲名称和歌曲的时间

[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:@{MPMediaItemPropertyArtist:@"陈奕迅",MPMediaItemPropertyAlbumTitle:@"拔河",MPMediaItemPropertyPlaybackDuration:@"280"}];

锁屏和快捷栏的控制

如果要实现在锁屏和快捷栏上控制音乐播放,要实现下面这个接口

//响应远程音乐播放控制消息
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        switch (receivedEvent.subtype) {
            case UIEventSubtypeRemoteControlPlay:
                [player play];
                NSLog(@"暂停播放");
                break;
            case UIEventSubtypeRemoteControlPause:
                [player pause];
                NSLog(@"继续播放");
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                NSLog(@"下一曲");
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                NSLog(@"上一曲");
                break;
            default:
                break;
        }
    }
}

UIEvent是个枚举,包含了要控制的行为

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

通过具体的值,调用不同的函数来实现控制音视频的播放。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值