Play background sound on iphone

How to play background sound while my application is running?

Thanks.

+3
source share
2 answers

Good. This is a background sound solution on iOS4 and iOS5 (it definitely works before iOS 5.0.1), and I tested it only with AVPlayer. It should probably work for MPMusicPlayerController as well.

Necessary framework:

  • AVFoundation.framework
  • AudioToolbox.framework

In Info.plistfor the key UIBackgroundModesadd audio.

In MyAppDelegate.h:

  • reference <AVFoundation/AVFoundation.h>and<AudioToolbox/AudioToolbox.h>
  • implement protocol AVAudioSessionDelegate:

    @interface MyAppDelegate : NSObject <UIApplicationDelegate, AVAudioSessionDelegate>
    
  • define method ensureAudio:

    // Ensures the audio routes are setup correctly
    - (BOOL) ensureAudio;
    

In MyAppDelegate.m:

  • implement the method 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 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];
     }];
    
  • shoooooooooooooo !

+9

- setCategory AVAudioSessionCategoryPlayAndRecord.

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

Source: https://habr.com/ru/post/1709039/


All Articles