iOS实现锁屏页面控制音乐播放
本文实例为大家分享了iOS锁屏页面控制音乐播放的具体代码,供大家参考,具体内容如下
//1、调整音频会话设置,确保应用进入后台或静音开关已开启时音频仍将继续播放 //2、锁屏状态下显示媒体信息 //3、锁屏上的空间可以控制音频播放 #import"ViewController.h" #import#import @interfaceViewController() @property(nonatomic,strong)AVAudioPlayer*audioPlayer; @property(weak,nonatomic)UIButton*playButton; @end @implementationViewController -(void)viewDidLoad{ [superviewDidLoad]; UIButton*playButton=[UIButtonbuttonWithType:UIButtonTypeSystem]; playButton.frame=CGRectMake(0,0,200,40); playButton.center=self.view.center; [playButtonsetTitle:@"在后台播放音频"forState:UIControlStateNormal]; [playButtonaddTarget:selfaction:@selector(playMusicInBackground:)forControlEvents:UIControlEventTouchUpInside]; [self.viewaddSubview:playButton]; NSError*playerInitError=nil; NSString*audioPath= [[NSBundlemainBundle]pathForResource:@"background_audio" ofType:@"mp3"]; NSURL*audioURL=[NSURLfileURLWithPath:audioPath]; self.audioPlayer=[[AVAudioPlayeralloc] initWithContentsOfURL:audioURL error:&playerInitError]; AVAudioSession*session=[AVAudioSessionsharedInstance]; NSError*activeError=nil; if(![sessionsetActive:YESerror:&activeError]){ NSLog(@"Failedtosetactiveaudiosession!"); } //No.1 //开始写代码,调整音频会话设置,确保即便应用进入后台或静音开关已开启,音频仍将继续播放 NSError*categoryError=nil; [sessionsetCategory:AVAudioSessionCategoryPlaybackerror:&categoryError]; //end_code } -(void)playMusicInBackground:(id)sender{ if([self.audioPlayerisPlaying]){ [self.audioPlayerstop]; [self.playButtonsetTitle:@"正在播放音乐" forState:UIControlStateNormal]; }else{ UIImage*lockImage=[UIImageimageNamed:@"belongToMe.jpg"]; MPMediaItemArtwork*artwork= [[MPMediaItemArtworkalloc]initWithImage:lockImage]; NSDictionary*mediaDict= @{ MPMediaItemPropertyTitle:@"BackgroundTaskAudio", MPMediaItemPropertyMediaType:@(MPMediaTypeAnyAudio), MPMediaItemPropertyPlaybackDuration: @(self.audioPlayer.duration), MPNowPlayingInfoPropertyPlaybackRate:@1.0, MPNowPlayingInfoPropertyElapsedPlaybackTime: @(self.audioPlayer.currentTime), MPMediaItemPropertyAlbumArtist:@"SomeUser", MPMediaItemPropertyArtist:@"SomeUser", MPMediaItemPropertyArtwork:artwork}; [self.audioPlayerplay]; [self.playButtonsetTitle:@"停止播放后台音乐" forState:UIControlStateNormal]; //No.2 //开始写代码,将媒体信息显示在锁定屏幕上,并使锁屏上控件可以控制音频播放 [[UIApplicationsharedApplication]beginReceivingRemoteControlEvents]; //end_code } } //No.3 //开始写代码,响应远程控制,使得进入锁屏状态后可以控制音乐“播放”和“暂停” -(void)remoteControlReceivedWithEvent:(UIEvent*)receivedEvent{ if(receivedEvent.type==UIEventTypeRemoteControl){ switch(receivedEvent.subtype){ caseUIEventSubtypeRemoteControlPlay: [self.audioPlayerplay]; break; caseUIEventSubtypeRemoteControlPause: [self.audioPlayerpause]; break; default: NSLog(@"没有处理过这个事件------receivedEvent.subtype==%ld",(long)receivedEvent.subtype); break; } } } //end_code -(void)didReceiveMemoryWarning{ [superdidReceiveMemoryWarning]; } @end
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。