按下主页按钮时在后台播放音乐

时间:2015-09-03 07:25:51

标签: ios objective-c avaudioplayer

我想播放音乐背景,为此我在info.plist中进行了更改。我将应用程序设置为不在后台运行应用播放音频所需的背景模式

我在AppDelegate中添加了这个:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [[AVAudioSession sharedInstance] setDelegate:self];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error = nil;
    NSLog(@"Activating audio session");
    if (![audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:&error]) {
        NSLog(@"Unable to set audio session category: %@", error);
    }
    BOOL result = [audioSession setActive:YES error:&error];
    if (!result) {
        NSLog(@"Error activating audio session: %@", error);
    }
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

}

但是当我按下主页按钮时,音乐不再播放了。请问我哪里错了?

2 个答案:

答案 0 :(得分:2)

您应该将var managedObjectContext = NSManagedObjectContext(concurrencyType:.MainQueueConcurrencyType) 设置为NO

答案 1 :(得分:2)

enter image description here

在homeBtnEventMethod

的homeBtn屏幕上播放音频 viewController.h #import <AVFoundation/AVAudioPlayer.h>

中的

1。)

2。)@property (nonatomic, strong) AVAudioPlayer *theAudio;

3。)在viewDidLoad中的 viewController.m

 NSError *error = nil;
self.theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];

4。)- (IBAction)homeBtnTpd { [self.theAudio play]; }