Reputation: 714
I think everything is in the title.
I have a UIWebiew that plays music, and when the user use the power or home button, putting the app in background, I want the music to keep playing.
Is it possible ?
Thank you for your help !
Upvotes: 1
Views: 2944
Reputation: 1590
Yes it is possible. You need to do:
@import AVFoundation;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
Required background modes: App plays audio or streams audio/video using AirPlay
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
Upvotes: 0
Reputation: 2101
A little tricky but it is possible. From the official Apple doc below:
https://developer.apple.com/library/ios/qa/qa1668/_index.html
You need to first declare in your plist the UIBackgroundModes
for audio
, and then write the following code snippet in your AppDelegate
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
if (!success) { /* handle the error condition */ }
NSError *activationError = nil;
success = [audioSession setActive:YES error:&activationError];
if (!success) { /* handle the error condition */ }
Now when you have audio playing from a UIWebView, you can go to the home screen, change to another app, or lock the screen and the audio will continue playing.
Upvotes: 3
Reputation: 450
You can't actually do this with a UIWebView, but you can still do it. This method still streams the audio off of an online resource via a URL. Here is some code to help you. Now, lets say, you want to stream the audio when the app exits for a video, then its very similar, but uses the MediaPlayer framework instead of AVAudioPlayer framework.
NSURL *url = [NSURL URLWithString:@"http://website.com/audio.mp3"];
NSData *data = [NSData dataWithContentsOfURL:url];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
[audioPlayer play];
Upvotes: 5
Reputation: 130183
I don't believe this is possible, and even after checking UIWebView
's documentation I only found the following three attributes related to media playback.
allowsInlineMediaPlayback property
mediaPlaybackRequiresUserAction property
mediaPlaybackAllowsAirPlay property
Unfortunately, none of them do this.
Upvotes: 1