AVAudioPlayer暂停后恢复背景音频 [英] Resume background audio after AVAudioPlayer is paused

查看:528
本文介绍了AVAudioPlayer暂停后恢复背景音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个iPhone应用程序,允许其他应用程序在后台播放音频。为此,我按如下方式初始化我的音频会话:

I've developed an iPhone application that allows other apps to play audio in the background. To achieve this, I initialize my audio session like this:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

在我的应用程序中的某个时刻,我提供了一个音频播放器,用AVAudioPlayer播放存储在CoreData中的一些文件。当用户点击播放按钮时,应暂停背景音频。当播放器完成或暂停时,背景音频应恢复播放。

At some point in my application I provide an audio player to play some files stored in CoreData with AVAudioPlayer. When the user hits the play button, the background audio should be paused. When the player has finished or is paused, the background audio should resume playback.

播放器播放完毕后重新开始播放

While resuming after the player has finished playback with

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation error:nil];
}

就像一个魅力,暂停后我会遇到简历。它应该在按钮的IBAction中以相同的方式工作

works like a charm, I get stuck with resume after pause. It should work the same way within the button's IBAction

-(IBAction)pausePlayer
{
    if (self.player.isPlaying) {
        [self.player pause];
        [[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation error:nil];
    }
}

但我总是得到同样的错误:

but I always get the same error:

Unable to deactivate audio session. Error: Error Domain=NSOSStatusErrorDomain Code=560030580 "The operation couldn’t be completed. (OSStatus error 560030580.)"

为什么在这种情况下无法取消激活AudioSession的任何建议?

Any suggestions why it is impossible to inactivate the AudioSession in this case?

推荐答案

我试了3个小时终于搞定了这就是我所做的事情

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

这篇关于AVAudioPlayer暂停后恢复背景音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆