Linuxmint
Linuxmint

Reputation: 4746

Whats the simplest way to play a looping sound?

What is the simplest way to play a looping sound in an iPhone app?

Upvotes: 2

Views: 5764

Answers (2)

John Parker
John Parker

Reputation: 54435

Probably the easiest solution would be to use an AVAudioPlayer with the numberOfLoops: set to a negative integer.

// *** 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];

You should also remember to set the appropriate audio category. (See the AVAudioSession setCategory:error: method.)

Finally, you'll need to add the AVFoundation library to your project. To do this, alt click on your project's target in the Groups & Files column in Xcode, and select "Get Info". Then select the General tab, click the + in the bottom "Linked Libraries" pane and select "AVFoundation.framework".

Upvotes: 15

Brenton Morse
Brenton Morse

Reputation: 2567

The easiest way would be to use an AVAudioPlayer set to an infinite number of loops (or finite if that's what you need).

Something like:

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]; 

This will simply loop whatever audio file you have specified indefinitely. Set the number of loops to any positive integer if you have a finite number of times you want the audio file to loop.

Hope this helps.

Cheers.

Upvotes: 6

Related Questions