[英]Looping a sound file in 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
,解决方案将是这样的(使用ARC
)。
你需要在你的班级中定义一个变量......
@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);
}
使用AudioServicesAddSystemSoundCompletion函数注册回调,如AudioServicesPlaySystemSound函数说明所述。 计时器的问题是您可能无法在上一个声音完成时准确启动它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.