Search code examples
iphonesdkmp3avaudioplayernsdata

Get mp3 as NSData


I want to play a mp3 from my server with AVAudioPlayer. I am trying to do it by using

initWithData:(NSData *) error:(NSError **)

To do this I need to convert the mp3 to NSData then pass the NSData into my player. How do I convert the mp3 to NSData.


Solution

  • NSData has an -initWithContentsOfURL: (or +dataWithContentsOfURL:) method you could use.

    Or, you could use NSURLConnection to download your MP3 as NSData.

    I'd advise the second method, because it can be used asynchronously and doesn't block the main thread, unlike NSData's -initWithContentsOfURL: