iOS 잠 금 화면 제어 음악 재생 실현

본 논문 의 사례 는 iOS 잠 금 화면 에서 음악 재생 을 제어 하 는 구체 적 인 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.

//1、        ,                          
//2、            
//3、              

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface ViewController ()

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (weak, nonatomic) UIButton *playButton;

@end

@implementation ViewController

- (void)viewDidLoad {
 [super viewDidLoad];

 UIButton * playButton = [UIButton buttonWithType:UIButtonTypeSystem];
 playButton.frame = CGRectMake(0, 0, 200, 40);
 playButton.center = self.view.center;
 [playButton setTitle:@"       " forState:UIControlStateNormal];
 [playButton addTarget:self action:@selector(playMusicInBackground:) forControlEvents:UIControlEventTouchUpInside];
 [self.view addSubview:playButton];

 NSError *playerInitError = nil;

 NSString *audioPath =
 [[NSBundle mainBundle] pathForResource:@"background_audio"
         ofType:@"mp3"];

 NSURL *audioURL = [NSURL fileURLWithPath:audioPath];

 self.audioPlayer = [[AVAudioPlayer alloc]
      initWithContentsOfURL:audioURL
      error:&playerInitError];

 AVAudioSession *session = [AVAudioSession sharedInstance];

 NSError *activeError = nil;
 if (![session setActive:YES error:&activeError]) {
  NSLog(@"Failed to set active audio session!");
 }

 //No.1
 //     ,        ,                  ,        

 NSError *categoryError = nil;
 [session setCategory:AVAudioSessionCategoryPlayback error:&categoryError];


 //end_code


}
- (void)playMusicInBackground:(id)sender {

 if ([self.audioPlayer isPlaying]) {
  [self.audioPlayer stop];

  [self.playButton setTitle:@"      "
       forState:UIControlStateNormal];

 } else {
  UIImage *lockImage = [UIImage imageNamed:@"belongToMe.jpg"];

  MPMediaItemArtwork *artwork =
  [[MPMediaItemArtwork alloc] initWithImage:lockImage];

  NSDictionary *mediaDict =
  @{
   MPMediaItemPropertyTitle: @"BackgroundTask Audio",
   MPMediaItemPropertyMediaType: @(MPMediaTypeAnyAudio),
   MPMediaItemPropertyPlaybackDuration:
    @(self.audioPlayer.duration),
   MPNowPlayingInfoPropertyPlaybackRate: @1.0,
   MPNowPlayingInfoPropertyElapsedPlaybackTime:
    @(self.audioPlayer.currentTime),
   MPMediaItemPropertyAlbumArtist: @"Some User",
   MPMediaItemPropertyArtist: @"Some User",
   MPMediaItemPropertyArtwork: artwork };

  [self.audioPlayer play];

  [self.playButton setTitle:@"        "
       forState:UIControlStateNormal];

  //No.2
  //     ,             ,               


  [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];


  //end_code
 }
}

//No.3
//     ,      ,               “  ” “  ”


- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {

 if (receivedEvent.type == UIEventTypeRemoteControl) {
  switch (receivedEvent.subtype) {

   case UIEventSubtypeRemoteControlPlay:
    [self.audioPlayer play];
    break;

   case UIEventSubtypeRemoteControlPause:
    [self.audioPlayer pause];
    break;

   default:
    NSLog(@"         ------receivedEvent.subtype==%ld",(long)receivedEvent.subtype);
    break;
  }
 }
}


//end_code

- (void)didReceiveMemoryWarning {
 [super didReceiveMemoryWarning];
}

@end
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기