在Cocoa Touch中循环声音文件 [英] Looping a sound file in Cocoa Touch

查看:86
本文介绍了在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);
}


推荐答案

c $ c> AVAudioPlayer 而是,解决方案将是这样的(使用 ARC )。

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

这篇关于在Cocoa Touch中循环声音文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆