UIWebView Muted Sound in iOS6

If you happen to be using the HTML5 audio tag in your web application that you are displaying via a UIWebView, you may encounter an issue where the audio sound won’t seem to play. For example, let’s say you have the following HTML in your code and are displaying it in a UIWebView:

<audio id="some_sound">
  <source src="some_sound.mp3" type="audio/mpeg">
</audio>

And you attempt to play the audio tag via Javascript, which results in no sound actually playing:

document.getElementById('some_sound').play();

In this case, in order to play the sound, you will need to make sure to disable the mediaPlaybackRequiresUserAction property of the UIWebView:

webView.mediaPlaybackRequiresUserAction = NO;

Typically, UIWebView requires the user to interact with the audio tag (i.e. tap on the element in order to play it). However, disabling the mediaPlaybackRequiresUserAction property will allow you to use Javascript to play the sound.

Now let’s say you need the sound to play even when the application is in the background. In this case, there’s some additional code you will need. Add the following code before the UIWebView is added (in addition to the above code):

#import <AVFoundation/AVFoundation.h>

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

This will set the audio session for the application to “Playback” mode, and thus will allow you to play sound even when the app is in the background. You will know this is working when you see the “Play” icon in the status bar of your iDevice as the sound plays.

See stackoverflow.com