私のアプリにはAVAudioPlayerのインスタンスがあり、これは mp3 のシーケンスを再生し、次のものに切り替えinitWithData
ます:
ユーザーが画面をオフにしたり、バックグラウンドに移動したりしても、ユーザーがプレーヤーを聴き続けられるようにしたい. ユーザーがタップしたときに他のオーディオに切り替えるために使用できることは知ってremotecontrolevents
いますが、iPod プレーヤーのように自動的に切り替えることはできますか?
私のアプリにはAVAudioPlayerのインスタンスがあり、これは mp3 のシーケンスを再生し、次のものに切り替えinitWithData
ます:
ユーザーが画面をオフにしたり、バックグラウンドに移動したりしても、ユーザーがプレーヤーを聴き続けられるようにしたい. ユーザーがタップしたときに他のオーディオに切り替えるために使用できることは知ってremotecontrolevents
いますが、iPod プレーヤーのように自動的に切り替えることはできますか?
AVAudioPlayerDelegate
プロトコルを使用する必要があります。まず、インターフェースにそれを含めます。
@interface MyAppViewController : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *yourPlayer;
}
@property (nonatomic, retain) AVAudioPlayer *yourPlayer;
次に、実装では:
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
//This method is called once the file has finished playing
//Insert code here to play the next file
}
メソッド(またはメソッドを配置する場所)でdelegate
ofyourPlayer
を設定することを忘れないself
でください。viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad]
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
self.yourPlayer = [[AVAudioPlayer alloc] init];
self.yourPlayer.delegate = self;
}
また、info.plistの必須のバックグラウンドモードをアプリがオーディオを再生するように変更する必要があります
リモートコントロールイベントの登録を解除することを忘れないでください(viewDidUnload
):
[[UIApplication sharedApplication] endReceivingRemoteControlEvents]