简体   繁体   中英

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);
}

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

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM