简体   繁体   中英

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.

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

在此输入图像描述

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM