Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping Audio in Xcode

Im playing a sound in my app that I would like to loop. My research into this hasnt quite sorted my issue.

my code .m

CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"ar4", CFSTR 
                                          ("wav"), NULL);


UInt32 soundID;
AudioServicesCreateSystemSoundID (soundFileURLRef, &soundID);
AudioServicesPlaySystemSound (soundID);

I think I need to put something like this in

numberOfLoops = -1;

But unsure how to implement in my code as I get undeclared error for numberOfLoops. Some advice would be very much appreciated

like image 415
JSA986 Avatar asked Dec 21 '22 19:12

JSA986


1 Answers

Something like this should do your problem:

    NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
    resourcePath = [resourcePath stringByAppendingString:@"/YOURMUSICNAME.mp3"];
    NSLog(@"Path to play: %@", resourcePath);
    NSError* err;

    //Initialize our player pointing to the path to our resource
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:
                 [NSURL fileURLWithPath:resourcePath] error:&err];

    if( err ){
        //bail!
        NSLog(@"Failed with reason: %@", [err localizedDescription]);
    }
    else{
        //set our delegate and begin playback
        player.delegate = self;
        [player play];
        player.numberOfLoops = -1;
        player.currentTime = 0;
        player.volume = 1.0;
    }

Then if you want to stop it:

[player stop];

or pause it :

[player pause];

and also import it in your header file:

#import <AVFoundation/AVFoundation.h>.   

You should to ofcourse declare it in your header, then synthesize it.

//.h and add the bold part:

@interface ViewController : UIViewController <AVAudioPlayerDelegate> {

AVAudioPlayer *player;
}
@property (nonatomic, retain) AVAudioPlayer *player;

//.m

@synthesize player;
like image 61
Bazinga Avatar answered Jan 08 '23 17:01

Bazinga