Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play sound in background using AVAudioPlayer without stopping ipod music

In my app at particular time i am alerting user with beep sound which i am playing using AVAudioPlayer.

Now i want this sound to be played even when app is in background. So i can achieve this by setting AVAudioSession category as AVAudioSessionCategoryPlayback and i also want that this sound should not stop the ipod music and i can do it with it setting AVAudioPlayer category AVAudioSessionCategoryAmbient.

But i want them together means sound should also play in background and it should also not stop the ipod music.

So how can i achieve this?

If it is not possible to play sound with AVAudioSessionCategoryAmbient category in background then any other workaround this?

Apologies if i am doing any mistake.

Thanks.

like image 633
Unnati Avatar asked Oct 05 '22 00:10

Unnati


1 Answers

you need to add one row in your project.plist file Required background modes like bellow image and set it.

enter image description here

and put bellow code in to your project appdelegate didFinishLaunchingWithOptions

 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    NSError *error;
    BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];
    if (!success) {
        //Handle error
        NSLog(@"%@", [error localizedDescription]);
              } else {
                  // Yay! It worked!
              }

its working for me hope its useful for you my frnd al the best.

UPDATE

You can't run AVAudioPlayer and the iPod player or MPMusicPlayer or MPMoviePlayer at the same time, without doing a bit more work. If you want easy, then use Audio Toolbox's System Sounds.

please refer this bellow link:-

iPhone AVAudioPlayer stopping background music

Please check bellow Link there are demo of Playing audio file in background. please check it

http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_background-audio/

like image 187
Nitin Gohel Avatar answered Oct 13 '22 11:10

Nitin Gohel