iOS/MacOS开发

ios background modes

2022-04-23  本文已影响0人  若水water
iOS APP的运行状态
后台模式 Background Modes
Background modes

例如音频播放

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //    后台播放音频设置
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    //    让APP支持接受远程控制事件
    [[UIApplication sharedApplication]beginReceivingRemoteControlEvents];
    
    _window = [[UIWindow alloc]initWithFrame:UIScreen.mainScreen.bounds];
    _window.backgroundColor = UIColor.whiteColor;
    _window.rootViewController = [[ViewController alloc]init];
    [_window makeKeyAndVisible];
    
    return YES;
}

//ViewController中播放音频
- (void)viewDidLoad {
    [super viewDidLoad];
//    播放背景音乐
    NSString *path = [[NSBundle mainBundle]pathForResource:@"01 丑八怪" ofType:@"mp3"];
    NSURL *url = [[NSURL alloc]initFileURLWithPath:path];
//    创建播放器,_player一定要设置成全局变量,否则没有声音
    _player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    [_player setVolume:1];
    _player.numberOfLoops = -1;//-1为一直循环
    _player.pan = 0.0;
    _player.rate = 1.0;
    [_player prepareToPlay];
    [_player play];//播放
}
最后别忘了在Background modes 里面勾选第一条
image.png
打开info.plist 文件,可以看到配置已经写入
info.plist
上一篇 下一篇

猜你喜欢

热点阅读