在View Controllers - iOS之间移动后恢复音频播放

时间:2015-02-12 17:30:10

标签: ios objective-c avaudioplayer

在我的项目中,我在viewDidLoad中播放了背景音乐,我还有另一个viewController,当我转到ViewController2时,音频暂停使用在viewWillDisappear中调用的[player pause];方法。我的问题是,当我回到ViewController1时,音频重新开始,而不是从停止的地方恢复。 这是我的代码:

1)playMusic(在ViewDidLoad中调用):

-(void) playMusic{
NSError *error;
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategorySoloAmbient error:&error];
NSString *path = [[NSBundle mainBundle]
                  pathForResource:kSongTitle ofType:kSongFormat];
NSURL *pathURL = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:pathURL error:&error];
[player setDelegate:self];
[player setNumberOfLoops:-1.0];
[player play];}

2)ViewWillDisappear:

-(void) viewWillDisappear:(BOOL)animated{
if (player.playing)
    [player pause];
[super viewWillDisappear:YES];}

3)resumeMusic(在viewWillAppear中调用):

-(void)resumeMusic{
if (!player){
    NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
    resourcePath = [resourcePath stringByAppendingString:kSongfullTitle];
    NSLog(@"Path to play: %@", resourcePath);
    NSError *err;
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:resourcePath] error:&err];
    if (err)
        NSLog(@"failed with reason: %@", [err localizedDescription]);
    else{
        player.delegate = self;
        [player play];
    }
} else {
    NSLog(@"resuming");
    [player play];
} }

1 个答案:

答案 0 :(得分:0)

嗯,玩家为零有点奇怪,所以首先要确保播放器定义为strong

@property (strong,nonatomic) AVAudioPlayer * player;

如果是这种情况,我建议采用不同的角度。由于ViewDidLoad只被调用一次 - 当分配viewController时。如果你再次到达那里,这意味着整个viewController已经发布,你可以毫不畏惧地重新分配player(音频会重新启动,但你没有真正的选择)

所以我建议不要在ViewDidLoad中播放,而只能在ViewWillAppear中播放(每次都会调用 - 也是第一次调用)

所以代码应该是:

-(void) initPlayer  //called from ViewDidLoad
{
    NSError *error;
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategorySoloAmbient error:&error];
    NSString *path = [[NSBundle mainBundle]
                      pathForResource:kSongTitle ofType:kSongFormat];
    NSURL *pathURL = [NSURL fileURLWithPath:path];
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:pathURL error:&error];
    [player setDelegate:self];
    [player setNumberOfLoops:-1.0];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [player play];
}

**选项2:**

如果你真的希望音频总是从点(不管是什么)恢复 - 这实际上取决于你想要做什么 - 将AVAudioPlayer移动到单身(SharedInstance)并引用它从你需要的任何地方