在iphone上播放背景音频

时间:2009-05-25 20:28:17

标签: iphone audio

如何在应用程序运行时播放背景音频?

感谢。

2 个答案:

答案 0 :(得分:9)

好。这是iOS4和iOS上的背景声音解决方案。 iOS5(绝对适用于iOS 5.0.1),我只用AVPlayer测试过它。它也可能适用于MPMusicPlayerController。

必需的框架:

  • AVFoundation.framework
  • AudioToolbox.framework

Info.plist中,对于密钥UIBackgroundModes,请添加audio

MyAppDelegate.h

  • 参考<AVFoundation/AVFoundation.h>&amp; <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:方法中,在分配根视图控制器之前,运行[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
    {
    
    }
    
  • 确保您的应用继续在后台运行。如果你愿意,你可以使用ol [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler],但我认为有更好的方法。

  • 播放实际音频(注意我正在使用ARC,这就是没有release次呼叫的原因):

    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];
     }];
    
  • 它真的很棒!

答案 1 :(得分:0)

如果您还使用自己的应用进行录制 - 那么请不要忘记将setCategory更改为AVAudioSessionCategoryPlayAndRecord。在其他情况下,您将无法录制

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error:&setCategoryErr];