我想通过打开开关来播放音频循环,但是我不希望在开关关闭之前循环结束。当循环结束时,我希望它从头开始就可以连续。

最佳答案

尝试这样的事情。注意-1告诉音乐无限期重复:

将此文件导入文件顶部:

#import <AVFoundation/AVFoundation.h>

然后使用它:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:resourcePath ofType:@"caf"];

NSError *activationError = nil;
NSError *audioPlayerInitError = nil;
[[AVAudioSession sharedInstance] setActive: YES error:&activationError];

NSURL *newURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:newURL error:&audioPlayerInitError];

[newPlayer prepareToPlay];
[newPlayer setVolume:.8];
[newPlayer setNumberOfLoops:-1]; // -1 means play indefintely
[newPlayer setDelegate: self];
[newPlayer play];
[newPlayer release];

然后停止它,您可以这样做:
if ([newPlayer isPlaying]) {
    [newPlayer stop];
}

10-07 20:04