Thursday, June 6, 2013

AVAudioPlayer initWithData example in Objective C (iOS).

AVAudioPlayer initWithData

Initializes and returns an audio player for playing a designated memory buffer.

- (id)initWithData:(NSData *)data error:(NSError **)outError

Parameters of [AVAudioPlayer initWithData]
A block of data containing a sound to play. The audio data must be in a format supported by Core Audio. For a list of supported formats, see “Using Audio” in Multimedia Programming Guide.
Pass in the address of a nil-initialized NSError object. If an error occurs, upon return the NSError object describes the error. If you do not want error information, pass in NULL.

Return Value of [AVAudioPlayer initWithData]
On success, an initialized AVAudioPlayer object. If nil, the outError parameter contains a code that describes the problem.

AVAudioPlayer initWithData example.
NSString *audioFile = [NSString stringWithFormat:@"%@/%@.caf", [[NSBundle mainBundle] resourcePath], @"audiofile"];
NSData *audioData = [NSData dataWithContentsOfMappedFile:audioFile];

NSError *err;
AVAudioPlayer *audioPlayer = [(AVAudioPlayer*)[AVAudioPlayer alloc] initWithData:audioData error:&err];

audioPlayer.delegate = self;
[audioPlayer play];

Example of [AVAudioPlayer initWithData].
NSError* error = nil;
self.songView.player = [[AVAudioPlayer alloc] initWithData:musicData error:&error];
if (error)
    NSLog(@"Error with initWithData: %@", [error localizedDescription]);

AVAudioPlayer initWithData example.
- (void)getAudioFromNet {

NSURL *url = [NSURL URLWithString:@\"\"]; //Example URL to the funny song I've created some time ago
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];


- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
    if (data==nil) {
data = [[NSMutableData alloc] initWithCapacity:2048];
    [data appendData:incrementalData];

- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {

player = [[AVAudioPlayer alloc] initWithData:data error: nil];
[player setVolume:0.1];
[player play];


End of AVAudioPlayer initWithData example article.