简体   繁体   English

iPhone应用程序允许继续播放背景音乐

[英]iphone app allow background music to continue to play

When I launch my iPhone game as soon as a sound plays the background music or podcast that is playing stops. 当我在声音播放时启动我的iPhone游戏时,播放的背景音乐或播客停止播放。 I noticed other games allow background audio to continue to play. 我注意到其他游戏允许继续播放背景音频。

How is this possible? 这怎么可能? Do I need to override a method in my App Delegate? 我是否需要覆盖App Delegate中的方法?

Place this line in your application:didFinishLaunchingWithOptions: method of your AppDelegate or in general before using the audio player. 将此行放在您的application:didFinishLaunchingWithOptions: AppDelegate方法,或者在使用音频播放器之前。

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

According to the documentation, the AVAudioSessionCategoryAmbient category is 根据文档, AVAudioSessionCategoryAmbient类别是

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. 此类别也适用于“播放”风格的应用程序,例如用户在iPod音频上播放的虚拟钢琴。 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). 屏幕锁定和静音开关(在iPhone上称为Ring / Silent开关)可以使您的音频静音。

If you want also to ensure that no error occurred you have to check the return value 如果您还想确保没有发生错误,则必须检查返回值

NSError *error;
BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];
if (!success) {
     //Handle error
     NSLog(@"%@", [error localizedDescription]);
} else {
   // Yay! It worked!      
}

As a final remark, don't forget to link the AVFoundation framework to your project and import it. 最后,请不要忘记将AVFoundation框架链接到您的项目并导入它。

#import <AVFoundation/AVFoundation.h>

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

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