当App进入后台时,如何停止在ViewController中实现的背景音乐

时间:2021-10-03 19:00:52

I would like to know how to stop background music (property of ViewController) when the app enters background. I think it's in the AppDelegate but I have no idea how to implement the code, or how to access the ViewController from the AppDelegate. Thanks !

我想知道当应用程序进入后台时如何停止背景音乐(ViewController的属性)。我认为它在AppDelegate中,但我不知道如何实现代码,或者如何从AppDelegate访问ViewController。谢谢 !

1 个解决方案

#1


0  

In your AppDelegate.m add the following to applicationDidEnterBackground:

在AppDelegate.m中,将以下内容添加到applicationDidEnterBackground:

[[NSNotificationCenter defaultCenter]] postNotificationName:@"SOUND_OFF" object:nil userInfo:nil];

[[NSNotificationCenter defaultCenter]] postNotificationName:@“SOUND_OFF”对象:nil userInfo:nil];

Then in your viewcontroller where you have the property for the background music, either in viewDidLoad or init

然后在viewcontroller中,您可以在viewDidLoad或init中获得背景音乐的属性

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopMusic:) name:@"SOUND_OFF" object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopMusic :) name:@“SOUND_OFF”object:nil];

add your method to the viewcontroller

将您的方法添加到viewcontroller

-(void)stopMusic:(NSNotification*)notification {
    //code to stop music
}

#1


0  

In your AppDelegate.m add the following to applicationDidEnterBackground:

在AppDelegate.m中,将以下内容添加到applicationDidEnterBackground:

[[NSNotificationCenter defaultCenter]] postNotificationName:@"SOUND_OFF" object:nil userInfo:nil];

[[NSNotificationCenter defaultCenter]] postNotificationName:@“SOUND_OFF”对象:nil userInfo:nil];

Then in your viewcontroller where you have the property for the background music, either in viewDidLoad or init

然后在viewcontroller中,您可以在viewDidLoad或init中获得背景音乐的属性

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopMusic:) name:@"SOUND_OFF" object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopMusic :) name:@“SOUND_OFF”object:nil];

add your method to the viewcontroller

将您的方法添加到viewcontroller

-(void)stopMusic:(NSNotification*)notification {
    //code to stop music
}