2012-07-07 166 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