iPhone Playing audio in the background

    I hope someone helps with this little guide on writing an iPhone client for Internet radio. Recently, I needed to write this. For self-educational purposes. I’ll try to cover the topic as broadly as possible in the future, but now I would like to focus on a specific point that made me more difficult than today, namely on playing the radio in the background.

    To do this, we need a couple of simple manipulations.
    First, we need to inform our application that it should play music even after clicking on “HOME”.
    This is done in the project’s Info.plist file:

    Select the file in Project Navigator
    image

    . Right-click on the empty space and select “Add row” "
    image

    In the" Key "field, enter" Required background modes ",
    image

    this will create an array for us, we will add “App plays audio” as the value for the first element.
    image

    Everything, our program knows that in the background it should not fall asleep completely, but should continue to play music.
    Another quick way to do the same is to open Info.plist with a regular editor (in fact it’s just an XML file) and add
    UIBackgroundModesaudio


    Now initialize our player.
    In general, the iOS SDK has several different classes for working with sound. At first I used AVQueuePlayer , then I decided to give preference to AVPlayer as the most flexible in my opinion.
    In any case, AVFoundation will help you to work with audio.

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Convert the file path to a URL.
        NSString *urlAddress = @"http://www.example.com/stream";
        //Create a URL object.
        NSURL *urlStream = [NSURL URLWithString:urlAddress];  
        AVPlayer *player = [[AVPlayer alloc] initWithURL:urlStream];    
        //Starts playback
        [player play];
    }
    


    Now create a session:
        // очень важная строчка, она должна быть ПОСЛЕ инициализации плеера.
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    


    That's basically all, the player can and will work in the background. You can minimize the program by clicking on “Home” and the music will not stop.

    And the most important point: for some reason, background audio playback does not work in the simulator, so it is mandatory to run and test on the device.

    Also popular now: