在Cocoa Touch中循环播放一个声音文件

我试图在视图加载时播放声音,并在整个应用程序中重复播放音乐,即使从不同的视图切换。 它一旦加载视图就会播放,并在切换到不同的视图后继续播放,但我无法循环播放。 我正在使用的声音。 任何帮助让我循环将是真棒

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

尝试使用AVAudioPlayer ,而解决scheme将是这样的(使用ARC )。


你需要在你的课堂上定义一个variables…

 @interface MyClass : AnyParentClass { AVAudioPlayer *audioPlayer; } // ... @end 

…你可以把下面的代码放在你的任何方法中开始播放…

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

…停止播放是非常容易的。

 if (audioPlayer) [audioPlayer stop]; 

尝试将您的代码移动到您的应用程序委托中,并使用重复的NSTimer重复您的播放操作。

示例代码:

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

如AudioServicesPlaySystemSound函数描述build议的,使用AudioServicesAddSystemSoundCompletion函数注册一个callback函数。 定时器的问题是,您可能无法正确启动前一个声音完成。