Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

objective c - 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. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

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.

#import <AVFoundation/AVFoundation.h>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...