简体   繁体   中英

How can I play continuous music in the background when my iPhone app is running?

I want to run light music (non-stop) when user is running my application actively. When user exits my application, then the music will be stopped automatically. I tried the following code to execute continuous music play (that is, play the music on a loop). But it doesn't actually loop; it ends the music once said music is completed.

- (void) PlayLoopMusic {
    NSString* path;
    NSURL* url;
    path = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
    url = [NSURL fileURLWithPath:path];

    player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    [player prepareToPlay];
    [player setVolume: 0.030];
    [player setDelegate: self];

    // Start playing it while starting the game ...
    [player play];
}

Could someone please suggest methods to achieve looping, continuous music?

I haven't had an opportunity to test this yet, but have you tried setting the numberOfLoops property to a negative value? The AVAudioPlayer API docs indicate that this is the correct way to get the sound to loop indefinitely.

set,

player.numberOfLoops = -1;

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