user1677210
user1677210

Reputation: 169

Looping a sound file in Cocoa Touch

I'm trying to get a sound to play once the view loads and repeat the music throughout the app even while switching from different views. It does play once the view is loaded and continues after switching to different views but I can't get it to loop. I am using for the sounds. Any help to get me to loop would be awesome

-(void)viewDidLoad {

    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef    soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef)@"beat", CFSTR ("mp3"), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
}

Upvotes: 1

Views: 1009

Answers (3)

holex
holex

Reputation: 24041

try to use the AVAudioPlayer instead, the solution would be something like this (with using ARC).


you need to define a variable in you class...

@interface MyClass : AnyParentClass {
    AVAudioPlayer *audioPlayer;
}

// ...

@end

...and you can put the following code in any of your methods to start playing...

NSURL *urlForSoundFile = // ... whatever but it must be a valid URL for your sound file
NSError *error;

if (audioPlayer == nil) {
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:urlForSoundFile error:&error];
    if (audioPlayer) {
        [audioPlayer setNumberOfLoops:-1]; // -1 for the forever looping
        [audioPlayer prepareToPlay];
        [audioPlayer play];
    } else {
        NSLog(@"%@", error);
    }
}

...to stop the playing is very easy.

if (audioPlayer) [audioPlayer stop];

Upvotes: 3

David Hoerl
David Hoerl

Reputation: 41642

Register a callback using the AudioServicesAddSystemSoundCompletion function, as the AudioServicesPlaySystemSound function description advises. The problem with the timer is you may not start it exactly when the previous sound has finished.

Upvotes: 0

Bartu
Bartu

Reputation: 2210

Try moving you code into your Application Delegate and use a repeating NSTimer to repeat your playing action.

Example code:

// appDelegate.h
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
     UInt32 soundID;
}

//appDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef    soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef)@"beat", CFSTR ("mp3"), NULL);
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);


    [NSTimer scheduledTimerWithTimeInterval:lenghtOfSound target:self selector:@selector(tick:) userInfo:nil repeats:YES];
    return YES;
}

-(void)tick:(NSTimer *)timer
{
   AudioServicesPlaySystemSound(soundID);
}

Upvotes: 0

Related Questions