Tulon
Tulon

Reputation: 4126

Audio isn't playing in background mode

I want to play an "audio" after 5 seconds when my app goes in background mode. The NSTimer triggered correctly. I am getting the NSLog(@"repeat"); after 5 seconds. But, some how the audio isn't playing. I enable Background Modes in my target. I try with many other solution, found here in stackoverflow, but no luck. Can any one provide me the right solution.

In my appdelegate.h file:

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    NSTimer* timer;
}

@property (strong, nonatomic) UIWindow *window;

@property (nonatomic, strong) NSString *musicName;
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

In my appdelegate.m file:

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

@synthesize
musicName,
audioPlayer;

-(void) playAlarmSound
{
    musicName = @"note3BreakOf.mp3";
    // Construct URL to sound file
    NSString *path = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], musicName];
    NSURL *soundUrl = [NSURL fileURLWithPath:path];

    // Create audio player object and initialize with URL to sound
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self playAlarmSound];
    return YES;
}

-(void)methodRunAfterBackground
{
    [audioPlayer play];
    [timer invalidate];
    NSLog(@"repeat");
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UIApplication *app = [UIApplication sharedApplication];

    //create new uiBackgroundTask
    __block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    //and create new timer with async call:
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //run function methodRunAfterBackground
        timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(methodRunAfterBackground) userInfo:nil repeats:NO];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    });
}

Upvotes: 1

Views: 790

Answers (3)

Pratibha Gupta
Pratibha Gupta

Reputation: 21

You can do this by making the app active background. I am doing this in my app. I am using location manager api to make the app active in background. Then start playing a audio in background with the help of timer. You can use this link https://github.com/voyage11/Location to make the app active in background.Hope this will help.

Upvotes: 0

matt
matt

Reputation: 535925

I want to play an "audio" after 5 seconds when my app goes in background mode

Well, you can't. If your app is not actively playing audio at the time it goes into the background, then when it goes into the background, it is suspended - regardless of your background settings. Your timer stops and the app sleeps.

(Many people solve this by playing a "silent" track as the app goes into the background, so that the app is playing something at that time, and can run in the background.)

Upvotes: 1

David Karlsson
David Karlsson

Reputation: 9716

You need to add "playsAudio" to your plist and set

  • AVAudioSession sharedInstance category to: AVAudioSessionCategoryPlayback
  • AVAudioSession sharedInstance setActive: YES
  • UIApplication sharedApplication beginReceivingRemoteControlEvents

Seems some of that might be deprecated, check here

In Objective-C:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

Upvotes: 1

Related Questions