簡體   English   中英

在Cocoa Touch中循環聲音文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM