Wednesday, June 5, 2013

AVAudioPlayer numberOfLoops example in Objective C (iOS).

AVAudioPlayer numberOfLoops

The number of times a sound will return to the beginning, upon reaching the end, to repeat playback.

@property NSInteger numberOfLoops

Discussion of [AVAudioPlayer numberOfLoops]
A value of 0, which is the default, means to play the sound once. Set a positive integer value to specify the number of times to return to the start and play again. For example, specifying a value of 1 results in a total of two plays of the sound. Set any negative integer value to loop the sound indefinitely until you call the stop method.

AVAudioPlayer numberOfLoops example.
// *** In your interface... ***
#import <AVFoundation/AVFoundation.h>


AVAudioPlayer *testAudioPlayer;

// *** Implementation... ***

// Load the audio data
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"sample_name" ofType:@"wav"];
NSData *sampleData = [[NSData alloc] initWithContentsOfFile:soundFilePath];
NSError *audioError = nil;

// Set up the audio player
testAudioPlayer = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError];
[sampleData release];

if(audioError != nil) {
    NSLog(@"An audio error occurred: \"%@\"", audioError);
else {
    [testAudioPlayer setNumberOfLoops: -1];
    [testAudioPlayer play];

// *** In your dealloc... ***
[testAudioPlayer release];

Example of [AVAudioPlayer numberOfLoops].
NSString *path = [[NSBundle mainBundle] pathForResource:@"yourAudioFileName" ofType:@"mp3"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:path];

AVAudioPlayer *_player = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
[file release];

_player.numberOfLoops = -1;
[_player prepareToPlay];
[_player play]; 

AVAudioPlayer numberOfLoops example.
- (void)viewDidLoad
[super viewDidLoad];

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audio.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;

if (audioPlayer == nil)
NSLog(@"No Sound");
[audioPlayer play];
NSLog(@"Sound Played");


End of AVAudioPlayer numberOfLoops example article.