我正在使用 AVAudioPlayer 的实例来播放音频文件。该应用程序配置为在后台播放音频,并设置了适当的音频会话。我也成功接收到远程控制事件。
这是代码:
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property (nonatomic) AVAudioPlayer *player;
@end
@implementation ViewController
@synthesize player;
- (BOOL)canBecomeFirstResponder { return YES; }
- (void)viewDidLoad
{
[super viewDidLoad];
// Turn on remote control event delivery
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
// Set ourselves as the first responder
[self becomeFirstResponder];
// Set the audio session
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
NSError *activationError = nil;
success = [audioSession setActive:YES error:&activationError];
// Play an mp3 with AVAudioPlayer
NSString *audioFileName = @"%@/Via_Aurora.mp3";
NSURL *audioURL = [NSURL fileURLWithPath:[NSString stringWithFormat:audioFileName, [[NSBundle mainBundle] resourcePath]]];
player = [[AVPlayer alloc] initWithURL:audioURL];
[player play];
}
- (void)viewWillDisappear:(BOOL)animated {
// Turn off remote control event delivery & Resign as first responder
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
// Don't forget to call super
[super viewWillDisappear:animated];
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
if (receivedEvent.type == UIEventTypeRemoteControl) {
switch (receivedEvent.subtype) {
case UIEventSubtypeRemoteControlPreviousTrack:
NSLog(@"prev");
break;
case UIEventSubtypeRemoteControlNextTrack:
NSLog(@"next");
break;
case UIEventSubtypeRemoteControlPlay:
[player play];
break;
case UIEventSubtypeRemoteControlPause:
[player pause];
break;
default:
break;
}
}
}
@end
当我运行应用程序时,音频会在视图加载时播放。当应用程序进入后台模式时,它会继续播放音频。我能够从控制中心成功暂停和/或播放音频(从应用程序或锁定屏幕访问)但是,如果我访问锁定屏幕音频控件并暂停播放器,音乐会暂停和锁定屏幕控件消失。我希望音乐暂停,但不会让控件消失。
在我使用的其他音频应用程序中,您可以暂停,然后播放锁定屏幕中的音频。我忽略了什么吗?这是做这样的事情的正确方法吗?