iOS SDK : playing music on the background and switching views

后端 未结 5 1464
北荒
北荒 2020-12-03 16:09

I am trying to play music in my application. The music works fine but after switching viewControllers and returning to the main menu, my music plays again! It means several

5条回答
  •  感动是毒
    2020-12-03 17:02

    First, viewDidLoad probably isn't a good place to be initializing your AVAudioPlayer, as the system may need to unload some of your components to reclaim memory (in viewDidUnload). You should probably be creating the AVAudioPlayer in your init method or similar.

    So what's happening is you end up creating a second AVAudioPlayer when the focus comes back to your application, and you're actually losing the reference to your first one. (Thus, also leaking memory.)

    If you want to start playing music when the view loads, you should additionally check its status before doing so:

    - (void)viewDidLoad {
        ...
        if (!myMusic.playing) {
            [myMusic play];
        }
        ...
    }
    

提交回复
热议问题