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
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
View의 레이아웃 방법을 AutoLayout에서 따뜻한 손 계산으로 하면 성능이 9.26배로 된 이야기이 기사는 의 15 일째 기사입니다. 어제는 에서 이었습니다. 손 계산을 권하는 의도는 없고, 특수한 상황하에서 계측한 내용입니다 화면 높이의 10 배 정도의 contentView가있는 UIScrollView 레이아...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.