33
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AVAudioPlayer でバックグラウンド再生

Posted at

シミュレータだとバックグラウンドにいっても音楽が再生され続けますが、実機だともろもろ設定や実装をしとかないと動かない。

Background Modes 追加

必要なスキーマすべてで以下を設定。

  • Xcode の Project Navigator -> プロジェクト選択 -> target の Capabilities タブ -> Background Modes を ON -> Audio and Airplay にチェック

AVAudioSession の設定

  • Xcode の Project Navigator -> プロジェクト選択 -> target の Build Phases タブ -> Link Binary With Libraries で AVFoundation.framework 追加
  • カテゴリ設定を適当なタイミングで。AppDelegate なり AVAudioPlayer を alloc する前なり。
    AVAudioSession* session = [AVAudioSession sharedInstance];
    NSError* error = nil;
    [session setCategory:AVAudioSessionCategoryPlayback error:&error];
    [session setActive:YES error:&error];

リモートコントロールイベントを受け取る && ファーストレスポンダになる

これやってなくてハマりました。

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self endReceivingRemoteControlEvents];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self beginReceivingRemoteControlEvents];
}

- (void) beginReceivingRemoteControlEvents {
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}
- (void) endReceivingRemoteControlEvents {
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    if (event.type == UIEventTypeRemoteControl) {
        switch (event.subtype) {
             // do something...
        }
    }
}
33
35
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?