1、申明后台模式播放
@property (nonatomic, strong) AVAudioSession *session;
- (void)viewDidLoad { [super viewDidLoad]; self.session = [AVAudioSession sharedInstance]; NSError *error; //申明后台模式播放 [self.session setCategory:AVAudioSessionCategoryPlayback error:&error]; if (error) { NSLog(@"Error setting audio session category: %@", error); } [self.session setActive:YES error:&error]; if (error) { NSLog(@"Error activating audio session: %@", error); } }
//使用户能够远程控制媒体播放器,通过耳机或者活动栏。 -(BOOL)canBecomeFirstResponder { return YES; }
- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; //注册远程控制事件 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [self becomeFirstResponder]; } - (void)viewWillDisappear:(BOOL)animated { [[UIApplication sharedApplication] endReceivingRemoteControlEvents]; [self resignFirstResponder]; [super viewWillDisappear:animated]; }
//接收和响应远程控制事件 - (void)remoteControlReceivedWithEvent: (UIEvent *) receivedEvent { if (receivedEvent.type == UIEventTypeRemoteControl) { switch (receivedEvent.subtype) { //调用各自的动作方法实现事件的定向 case UIEventSubtypeRemoteControlTogglePlayPause: [self togglePlay:self]; break; case UIEventSubtypeRemoteControlPreviousTrack: [self goToPrevTrack:self]; break; case UIEventSubtypeRemoteControlNextTrack: [self goToNextTrack:self]; break; default: break; } } }
2、实现播放器
@property (nonatomic, strong) AVPlayer *player; @property (nonatomic, strong) NSMutableArray *playlist; @property (nonatomic)NSInteger currentIndex;
- (void)viewDidLoad { [super viewDidLoad]; . . . self.playlist = [[NSMutableArray alloc] init]; self.player = [[AVPlayer alloc] init]; }
时间: 2024-10-31 10:47:00