Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • How to play music in the background using AVAudioplayer

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 856
    Comment on it

    Hi Readers,

    Many times we need to play music even app is in background. It is normal behavior of AVAudioPlayer to play sound when app is in foreground or active state. But to play sound, music or song even in background state can be achieved by following steps:

    First make the following changes in info.plist

    1. Application does not run in background : NO

    2. Required background modes:  item0 :App plays audio or streams audio/video using AirPlay

    Then add a global object into .h file or Object constructor as

    AVAudioPlayer *audioPlayer;

    Now put following code snippet into your class where you want to initialize audio player:

    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"your music file" ofType:@"mp3"]]; //1
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];  //2
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];  //3
    [[AVAudioSession sharedInstance] setActive: YES error: nil];  //4
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [audioPlayer play];

    Where line 1 and 2 are doing simply initialization of audio player with URL of your audio file.

    In line 3 we are getting singleton object of AVAudioSession which is provided by the SDK itself and it will remain same for all apps into device. Now we set category of AVAudioSession as AVAudioSessionCategoryPlayback which is commonly used to play files.

    In line 4 we are setting AVAudioSession as active so it will also work in the background.

    Now you must have clear idea that how AVAudioSession works. It will respond to latest event happening into device. Like if two application start playing song one after other then it will respond to last player song app.

    Hope it helps, Thanks for reading.


 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: