问题描述
我怎么能播放背景声音我的应用程序运行时?
How can I play a background audio while my application is running?
感谢。
推荐答案
好吧。这是对iOS4的&放大器背景音的溶液; iOS5的(肯定工程最多的iOS 5.0.1),而我只用AVPlayer进行了测试。它应该可能是MPMusicPlayerController工作了。
Okay. This is a solution for background sound on iOS4 & iOS5 (definitely works up to iOS 5.0.1), and I have tested it only with AVPlayer. It should probably work for MPMusicPlayerController too.
必需的框架:
-
AVFoundation.framework
-
AudioToolbox.framework
AVFoundation.framework
AudioToolbox.framework
在你的的Info.plist
,该键 UIBackgroundModes
添加音频
。
在 MyAppDelegate.h
:
- 参考
< AVFoundation / AVFoundation.h>
&安培;< AudioToolbox / AudioToolbox.h>
-
实施方案
AVAudioSessionDelegate
:
@interface MyAppDelegate : NSObject <UIApplicationDelegate, AVAudioSessionDelegate>
定义一个方法 ensureAudio
:
// Ensures the audio routes are setup correctly
- (BOOL) ensureAudio;
在 MyAppDelegate.m
:
-
实施
ensureAudio
方法:
- (BOOL) ensureAudio
{
// Registers this class as the delegate of the audio session (to get background sound)
[[AVAudioSession sharedInstance] setDelegate: self];
// Set category
NSError *categoryError = nil;
if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&categoryError]) {
NSLog(@"Audio session category could not be set");
return NO;
}
// Activate session
NSError *activationError = nil;
if (![[AVAudioSession sharedInstance] setActive: YES error: &activationError]) {
NSLog(@"Audio session could not be activated");
return NO;
}
// Allow the audio to mix with other apps (necessary for background sound)
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
return YES;
}
在的application:didFinishLaunchingWithOptions:
方法,你指定根视图控制器,运行之前 [自ensureAudio]
:
in the application:didFinishLaunchingWithOptions:
method, before you assign the root view controller, run [self ensureAudio]
:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Configure audio session
[self ensureAudio];
// Add the navigation controller's view to the window and display.
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
return YES;
}
实施这样的 AVAudioSessionDelegate
方法:
#pragma mark - AVAudioSessionDelegate
- (void) beginInterruption
{
}
- (void) endInterruption
{
// Sometimes the audio session will be reset/stopped by an interruption
[self ensureAudio];
}
- (void) inputIsAvailableChanged:(BOOL)isInputAvailable
{
}
确保您的应用程序将继续在后台运行。您可以使用醇' [UIApplication的sharedApplication] beginBackgroundTaskWithExpirationHandler]
如果你想要的,但我觉得有更好的办法。
ensure that your app continues to run in the background. You can use the ol' [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler]
if you want, but I think there are better ways.
发挥实际音频(请注意我用的弧线,这就是为什么没有发布
话费):
play the actual audio (note I'm using ARC, that's why there are no release
calls):
NSURL * file = [[NSBundle mainBundle] URLForResource:@"beep" withExtension:@"aif"];
AVURLAsset * asset = [[AVURLAsset alloc] initWithURL:file options:nil];
AVPlayerItem * item = [[AVPlayerItem alloc] initWithAsset:asset];
__block AVPlayer * player = [[AVPlayer alloc]initWithPlayerItem:item];
__block id finishObserver = [[NSNotificationCenter defaultCenter] addObserverForName:AVPlayerItemDidPlayToEndTimeNotification
object:player.currentItem
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
[[NSNotificationCenter defaultCenter] removeObserver:finishObserver];
// Reference the 'player' variable so ARC doesn't release it until it's
// finished playing.
player = nil;
}];
// Trigger asynchronous load
[asset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:@"tracks"] completionHandler:^{
// Start playing the beep (watch out - we're not on the main thread here)!
[player play];
}];
和它shooooooooooooould工作!
And it shooooooooooooould work!
这篇关于播放背景音乐在iPhone的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!