Search code examples
iosobjective-cipaduiwebviewnsdata

Load mp3 in UIWebView


I've an NSData obtained from a base64 NSString

NSString * fileBytes = @"...."; //base 64 string
NSData * bytes = [[NSData alloc] initWithBase64EncodedString:fileBytes options:0];

The I load the NSData into a UIWebView

[self.webView loadData:bytes
              MIMEType:@"audio/mpeg3"
      textEncodingName:@"UTF-8"
               baseURL:nil];

but this is what I see

enter image description here

I use the same procedure per many file types (PDF, png, jpg, doc, dock, xls ecc), and works perfectly.

Ideas ?


Solution

  • Recently I had such a situation and I searched a lot. At the end I found two ways to do that.

    1. Most nice way: Simply implement your code using MPMoviePlayerController

      MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL: myURL];
      [player prepareToPlay];
      [player.view setFrame: myView.bounds];  // player's frame must match parent's
      [myView addSubview: player.view];
      // ...
      [player play];    
      
    2. IF you really want to use UIWebView then think about embedded HTML5 <audio> tag.

      <audio controls> <source src="horse.ogg" type="audio/ogg"> <source src="horse.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio>

    and load the HTMLString with the method

    - (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
    

    but personally I would prefer the first solution with autoplay enabled.