Search code examples
iosaudiobackgroundm3u

iOS background Audio Stream (m3u) doesn't work on device (but does in simulator)


I have a UIWebView that loads a m3u from a url:

NSString *url = @"http://141.217.20.38:8000/live.m3u";
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];

followed by:

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];

This works on the simulator, but when I install it on a device (iPhone 5) via Xcode (with a development provisioning profile) the audio won't play in the background.

I'm not sure what I've missed, but any help would be greatly appreciated.


Solution

  • So, it looks like an AVSession also needs to be created. I added the following code, and it now works on the device the same as in the simulator

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    BOOL ok;
    NSError *setCategoryError = nil;
    ok = [audioSession setCategory:AVAudioSessionCategoryPlayback
                             error:&setCategoryError];
    if (!ok) {
        NSLog(@"%s setCategoryError=%@", __PRETTY_FUNCTION__, setCategoryError);
    }