繁体   English   中英

按下主屏幕按钮在后台播放音乐

[英]Play music in background when home button is press

我想播放音乐背景,为此我在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];

}

但是当我按下主屏幕按钮时音乐不再播放。 任何想法请我错了吗?

您应该将“ Applications does not run in background设置为“否”

在此处输入图片说明

并在homeBtnEventMethod的homeBtn屏幕上播放音频

1.)在viewController.h中 #import <AVFoundation/AVAudioPlayer.h>

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]; } - (IBAction)homeBtnTpd { [self.theAudio play]; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM