iOS how to don't stop music when the app start launching

心已入冬 提交于 2020-01-01 04:18:06

问题


I've noticed that when my app start, the music I'm listening is automatically stopped, and I've noticed that when I start some other apps, the music just continue... this means that I don't know how to manage the actual playing music in the device to let it plays or stop.

I'm developing a game with obj-c and cocos2d btw, I've searched but sadly I've found nothing... so here's my question, how can I let the music I'm listening with my device continue to play even if I start the app ?

edit: I'm using SimpleAudioEngine to start a background music and some sound effects in my app


回答1:


Place this line in your application:didFinishLaunchingWithOptions: method of your AppDelegate or in general before using the audio player.

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];

According to the documentation, the AVAudioSessionCategoryAmbient category is

for an app in which sound playback is nonprimary—that is, your app can be used successfully with the sound turned off. This category is also appropriate for “play along” style apps, such as a virtual piano that a user plays over iPod audio. When you use this category, audio from other apps mixes with your audio. Your audio is silenced by screen locking and by the Silent switch (called the Ring/Silent switch on iPhone).

please import AVFoundation/AVFoundation.h




回答2:


Swift:

Before playing enter this line:

let audioSession = AVAudioSession.sharedInstance()
if audioSession.otherAudioPlaying {
    _ = try? audioSession.setCategory(AVAudioSessionCategoryAmbient, withOptions: AVAudioSessionCategoryOptions.MixWithOthers)
}



回答3:


According to the docs:

You can activate the audio session at any time after setting its category, but it’s generally preferable to defer this call until your app begins audio playback. Deferring the call ensures that you won’t prematurely interrupt any other background audio that may be in progress.

Be sure not to be starting the audio session directly via its setActive method or indirectly via AVAudioEngine or other playback engine(s) immediately after the app launches. You should set only the category at this stage if you don't want your app to interrupt others on launch. If you're using AVAudioEngine, defer setting up the engine or connecting anything to the engine's mainMixerNode or outputNode until you actually need to start playing something.




回答4:


When your app starts playing music, it will pause any audio currently playing. For obvious reasons. If you want your music to carry on playing when the app launches then don't let the app play any music.



来源:https://stackoverflow.com/questions/18762544/ios-how-to-dont-stop-music-when-the-app-start-launching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!