2012-07-07 167 views
4

在我的應用程序中播放聲音,我想循環播放。我對此的研究還沒有完全整理我的問題。在Xcode中循環播放音頻

我的代碼.M

CFBundleRef mainBundle = CFBundleGetMainBundle(); 
CFURLRef soundFileURLRef; 
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"ar4", CFSTR 
              ("wav"), NULL); 


UInt32 soundID; 
AudioServicesCreateSystemSoundID (soundFileURLRef, &soundID); 
AudioServicesPlaySystemSound (soundID); 

我覺得我需要把這樣的事情在

numberOfLoops = -1; 

但不知道該如何在我的代碼實現,因爲我得到未申報的錯誤numberOfLoops。有些意見將非常感激

+0

是如何你在玩嗎? – Bazinga 2012-07-07 16:19:45

回答

11

像這樣的東西應該做你的問題:如果你想阻止它

NSString* resourcePath = [[NSBundle mainBundle] resourcePath]; 
    resourcePath = [resourcePath stringByAppendingString:@"/YOURMUSICNAME.mp3"]; 
    NSLog(@"Path to play: %@", resourcePath); 
    NSError* err; 

    //Initialize our player pointing to the path to our resource 
    player = [[AVAudioPlayer alloc] initWithContentsOfURL: 
       [NSURL fileURLWithPath:resourcePath] error:&err]; 

    if(err){ 
     //bail! 
     NSLog(@"Failed with reason: %@", [err localizedDescription]); 
    } 
    else{ 
     //set our delegate and begin playback 
     player.delegate = self; 
     [player play]; 
     player.numberOfLoops = -1; 
     player.currentTime = 0; 
     player.volume = 1.0; 
    } 

然後:

[player stop]; 

或暫停:

[player pause]; 

並將其導入到您的頭文件中:

#import <AVFoundation/AVFoundation.h>. 

你應該當然地在你的頭部聲明它,然後合成它。

//.h並添加大膽部分:

@interface ViewController中:UIViewController中< AVAudioPlayerDelegate> {

AVAudioPlayer *player; 
} 
@property (nonatomic, retain) AVAudioPlayer *player; 

//.m

@synthesize player; 
+0

感謝您的回覆,Ive遵循了您的代碼和說明,但隨處可得錯誤,我的代碼播放的聲音很好,希望我可以調整它,讓它循環播放音頻,而不是隻播放一次。 – JSA986 2012-07-07 16:05:13

+0

你不是在你的頭文件中啓動它,並在你的.m文件中合成它,這就是爲什麼你有錯誤。我的代碼在我的工作。我只是建議在這個更簡單的方法 – Bazinga 2012-07-07 16:11:34

+0

檢查編輯部分 – Bazinga 2012-07-07 16:16:36