Search code examples
objective-ccocoa-touchuiwebviewuiwebviewdelegate

UIWebView - Load local audio file into html via UIWebView


I am trying to send the path of a LOCAL mp3 file to javascript and from there creating an audio tag populated with the source. When I try this however, I am presented with a "cannot play audio file" message. The file itself is coming from the app specific sandbox so the path looks something like this

/Users/username/Library/Application Support/iPhone Simulator/6.0/Applications/818263D7-4246-4DEC-9186-6AC14F0175A3/Documents/audiofile.mp3

The problem is that I can play an mp3 from my desktop using the same method, just not one that is stored in the sandbox or local filesystem for the application itself. Here is the code I am using to get the path and send it to javascript through the webview. Any help would be greatly appreciated.

UIWebView *webContainer = [[UIWebView alloc] initWithFrame: self.view.bounds];
webContainer.backgroundColor = [UIColor grayColor];
webContainer.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight );
[webContainer setBackgroundColor:[UIColor clearColor]];
webContainer.delegate = self;
[self.view addSubview:webContainer];

NSString *imagePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,         NSUserDomainMask, YES) objectAtIndex:0];

NSString *imPath = [NSString stringWithFormat:@"%@/angels.mp3",imagePath];
imPath = [imPath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

[webContainer stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"setupAudio('%@');", imPath]];

Solution

  • If your path ends with 'audiofile.mp3' I don't think the file 'angels.mp3' will play.

    But you could just use the MPMoviePlayerController to play the file:

    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,             NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *audioPath = [NSString stringWithFormat:@"%@/angels.mp3",docPath];
    
    MPMoviePlayerController* moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL: audioPath];
    
    [moviePlayer.view  setFrame:self.view.bounds]; 
    
    //add it to your view
    [viewController.view addSubview:moviePlayer.view];
    
    //if you don't want any controls
    [moviePlayer setControlStyle:MPMovieControlStyleNone];
    
    //play!
    [moviePlayer prepareToPlay];
    

    Modified source from some example.

    Some other handy related question on this topic can be found here.