Wednesday, June 5, 2013

AVAudioPlayer initWithContentsOfURL error example in Objective C (iOS).

AVAudioPlayer initWithContentsOfURL error

Initializes and returns an audio player for playing a designated sound file.

- (id)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError

Parameters of [AVAudioPlayer initWithContentsOfURL error]
A URL identifying the sound file 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 initWithContentsOfURL error]
On success, an initialized AVAudioPlayer object. If nil, the outError parameter contains a code that describes the problem.

AVAudioPlayer initWithContentsOfURL error example.
/*sound loop stuff*/
NSString *soundFilePath = [[NSBundle mainBundle]
pathForResource:@"gong" ofType:@"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:fileURL error:nil];
[fileURL release];
self.loopSoundPlayer = newPlayer;
[newPlayer release];
[loopSoundPlayer setDelegate:self];
[loopSoundPlayer setNumberOfLoops:0];
[loopSoundPlayer prepareToPlay];

Example of [AVAudioPlayer initWithContentsOfURL error].
NSString *path = [[NSBundle mainBundle] pathForResource:@"PIC10"
        AVAudioPlayer* theAudio = [[AVAudioPlayer alloc]
initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
        theAudio.delegate = self;
        [theAudio play];

AVAudioPlayer initWithContentsOfURL error example.
                if ([resourceURL isFileURL]) {

                        [[AVAudioSession sharedInstance]
setCategory:AVAudioSessionCategoryPlayback error:nil];
                        audioFile.player = [[ AVAudioPlayer alloc ]
initWithContentsOfURL:resourceURL error:&error];
                } else {
                        NSData* data = [NSData dataWithContentsOfURL:resourceURL];
                        audioFile.player = [[ AVAudioPlayer alloc ] initWithData:data error:&error];

End of AVAudioPlayer initWithContentsOfURL error example article.