Resume background audio after AVAudioPlayer is paused

六眼飞鱼酱① 提交于 2019-12-03 17:22:15
suhail

I tried for 3 hours finally got it here is what I have done

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

@interface ViewController ()

    @property(strong, nonatomic)AVAudioPlayer *player;
    @property(strong)AVAudioSession *session;
@end

@implementation ViewController


- (IBAction)playsound:(id)sender

{

   NSURL *url=[[NSURL alloc]initWithString:[[NSBundle mainBundle]       pathForResource:@"sound" ofType:@"mp3"]];
    NSError *err;

    self.player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&err];
    [self.player setDelegate:self];
    [self.player setVolume:2.5];

    self.session=[AVAudioSession sharedInstance];

    [self.player prepareToPlay];
    [self.player play];

}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

{

    NSError *err;
    [self.session setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&err];



}


@end

It seems that the deactivation is too early. According to the AVAudioSession class reference "Deactivating your session will fail if any associated audio objects (such as queues, converters, players or recorders) are currently running."

There seem to be a few solutions:

  1. run the deactivation in a loop till it succeeds.

    This is advocated in http://iknowsomething.com/ios-sdk-spritekit-sound/

  2. postpone the deactivation, e.g till it is really necessary.

  3. when using e.g. the Audio Queue service, you may consider to stop immediately. (not tested)

    In a recording app with the possibility to listen the recordings, I only deactivate just before changing the category using the sequence: activate NO, setCategory and activate YES.

    See e.g. "While your app is running, Apple recommends that you deactivate your audio session before changing any of the set values" in Apple's Audio Session Programming Guide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!