Feb 19

The iPhone media player is very easy to use, but it only works in landscape mode and it seems designed more for video than audio.  If you wish to play an onboard MP3 or an MP3 file as it’s downloading (not really streaming, but progressive download) you have another option!  Use the audio player embedded with Safari running in a UIWebView.

Here’s how to do it without having to create a special window for it.  Instantiate an UIWebView object using a 1×1 pixel sized frame (here self.playerView is an instance variable on my controller and is NOT added as a subview)

UIWebView *webView = [[UIWebView alloc] initWithFrame: CGRectMake(0.0, 0.0, 1.0, 1.0)];
webView.delegate = self;
self.playerView = webView;
[webView release];

Then load your NSURLRequest.

NSURLRequest *request = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: myMP3URL] cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: myTimeoutValue];
[self.playerView loadRequest: request];
[request release];

That’s it!  When the request starts downloading the player with full controls will launch and your screen will look the the picture below.

Audio player launched from a UIWebView

Check out the web view delegate methods to learn more about controlling the behavior of the web view to suite your specific needs.

written by Jess \\ tags: ,

25 Responses to “A Simple Way To Play MP3 Audio Files”

  1. mike Says:

    Can you post a way to load xls and doc files? I’ve been fooling around with MIMEtypes and still can’t get it to load properly.

  2. Nick Says:

    @mike: Try opening the file in a UIWebView. That should launch the right viewer just like it does in Mail and Safari.

  3. iPhoneKicks.com Says:

    A Simple Way To Play MP3 Audio Files…

    You’ve been kicked (a good thing) – Trackback from iPhoneKicks.com – iPhone SDK links, community driven…

  4. Ecszavier Says:

    is it possible put an imagem on it instead of that symbol and url?

  5. Nick Says:

    @Ecszavier: Unfortunately not. This is the default audio player and you cannot change any aspect of it. There are other ways to play sound files, where you have the opportunity to create your own UI.

  6. sham Says:

    Once the particular mp3 is finished playing (or the user touches “Done”) in the player, the player fades away and the original UIWebView is shown.. Is there an event of some sort that the UIWebView can catch in-order to determine that the mp3 is finished or that the player is exiting?

    Thanks in advance.

    -ss

  7. Nick Says:

    @sham: I have not been able to discover any such event. In one app I traversed the view hierarchy to see if the player screen is still visible. But that is rather fragile and should be a last resort.

  8. need help with playing audio uninterrupted Says:

    Hi

    I need some serious help with with playing audio uninterrupted. I have a revolutionary idea for an app but I must find a way to make it work on iPhone (otherwise a work of 10 months may go down the drain).

    If you have any idea how this could be done (or know someone who can do it) PLEASE let me know how to contact you.
    Thanks.

  9. Nick Says:

    @need help: There are several ways to play audio on the iPhone. They mostly play without interruption until the end of the audio file. However there is nothing you can do within a third party application (developed with the official SDK) that will guarantee that the app is not interrupted. For example, an incoming phone call will always have priority. And you can’t prevent the user from pressing the Home button, which will also exit your app.

  10. Anil Says:

    The above method works fine for WAV files as well. But it fails in iPhone OS 3.0, can any one please help me, I need to use above method to run WAV files on my server in iPhone OS 3.0.
    Thanks in advance.

  11. Just me Says:

    hi, can you give full app code?

  12. Nick Says:

    I will try to pull together a complete project that illustrates this technique. I typically only post code snippets here on the blog because most of the iPhone apps that I write belong to my clients.

  13. Deaa Says:

    please help, I have a mp3 link which works in any browser in win and mac…..
    but not in iphone 3gs os 3.0…

    I tried by creating an application based on your code + tried to access the mp3’s url in iphone’s safari, in both cases I got : cannot play Movie – the file is not available !!

  14. Tim Says:

    I’m able to get this to work when I run the second block of code by itself, but when I run both blocks together it causes a EXC_BAD_ACCESS error. Things work great without that first block of code except for one thing: it plays the mp3 twice (when you click “done” the first time it goes to play it a second time). I’m hoping the first block of code will fix my problem if I can get it to work. Any ideas please?

    Do you have the source code that I can download as a complete project?

  15. Anthony Says:

    Would really like to see the source code of this if it’s possible mate?

  16. James A. Brannan Says:

    This was exactly what I was looking for….I was about to embark on coding the streaming, having not even thought about just letting Safari handle it. Much easier. Thanks.

  17. stinki Says:

    hi, thanks for that post. is it possible to load a xml file with some urls to the mp3-files and than play one a nother?

    thanks,
    stinki

  18. Nick Says:

    @stinki: The UIWebView cannot load and parse and XML for your MP3 URLs. You could load and parse the XML in your own code and then send the URLs to the UIWebView.

  19. James A. Brannan Says:

    It is working with a .pls also, only I have one bug I can’t seem to figure out. The playlist keeps reloading until I quit the app. Here’s my viewDidUnload code, anybody see something I’m forgetting?

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self.myWebView stopLoading];
    self.myWebView.delegate = nil;
    [self.navigationController popViewControllerAnimated:YES];

  20. brad Says:

    dumb question? how about playing an audio mp3 inside flash ?

  21. Ted Says:

    Kind of digging up old discussion here but I found a solution to the “playing twice” issue. Just keep a reference to the web view around. Each time you need to play a new MP3, deallocate it (remove it from the superview, release, etc.) and then create a new one. This ensures the web view is new and doesn’t play the previously played MP3 for some reason.

    I tried a bunch of stuff using UIWebViewDelegate and you just can’t jack into the order of events in any way to prevent previous playing, so this seems to be the only way. If you do it right you won’t have any memory leaks – run Instruments just to double check your logic.

  22. Ted Says:

    Alternatively you can:

    MPMoviePlayerController *mediaPlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:contentURL]];
    [mediaPlayer play];

    With this you can register an action with the MPMoviePlayerPlaybackDidFinishNotification by doing:

    // Register to receive a notification when the movie has finished playing.
    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(mediaPlayerPlaybackDidFinish:)
    name:MPMoviePlayerPlaybackDidFinishNotification
    object:mediaPlayer];

  23. Pierre Says:

    Hi,

    I use the same technics as you explain but sometimes, when after clicking on the “done” button, view dismiss and automaticaly restart after 1 second.

    Does anyone get the same problem?

    PS: Sorry for my English, I’m French man 🙂

  24. Xavier Says:

    Just an FYI that you can now play .mp3 files (and other file types) using the MPMoviePlayerController. I used the code below in my application:
    MPMoviePlayerController *playerViewController;
    NSURL *movieURL = [NSURL URLWithString:myMovieStringName];
    playerViewController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    playerViewController.controlStyle = MPMovieControlStyleFullscreen;
    playerViewController.shouldAutoplay = YES;

    [[playerViewController view] setFrame: CGRectMake(0.0, 0.0, 350.0, 250.0)]; // 2X the native resolution
    [self.playerView addSubview: [playerViewController view]];

  25. sana abbes Says:

    Hello everyone, I’m debutante developing ios, I pose a question: what type playerView?
    I am trying to make an MP3 player integrated into an application, ie when I click a button reading audio clip.
    please help me : ( , Thanks.

Leave a Reply