2014-09-22 66 views
-3

该代码假设声音是yes或yes 3播放时单击,但我得到一个错误,然后我开始调试,说rand不能静态分配,但我不能把一个*因为它是一个整数。当我这样做时,出现转换错误。我也尝试在声音之前放置一个*,并解决了错误问题,但是当按钮被点击时它不会播放任何东西。那么我该怎么做?指针循环到整数转换?

#import "ViewController.h" 
#import <AVFoundation/AVAudioPlayer.h> 

@interface ViewController() 

@end 

@implementation 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 

}//this is where the error breakpoint is that you show me how to make 

- (IBAction)Yes { 

    NSInteger rand = arc4random_uniform(2); 

    NSString sound = rand == 0 ? @"yes" : @"yes 3"; 

    NSURL *url = [[NSBundle mainBundle] URLForResource:sound withExtension:@"mp3"]; 


    AVAudioPlayer* audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; 

    [audioPlayer play]; 
} 

@end 

回答

0

我以前见过很多次了,这与你的音频播放器变量在它有机会播放文件之前被释放有关。

您需要为您的标题的音频播放器创建一个属性:

@property (nonatomic, strong) AVAudioPlayer *audioPlayer; 

然后在您的方法访问该属性,而不是局部变量:

- (IBAction)YES { 
    NSInteger rand = arc4random_uniform(2); 
    NSString *sound = rand == 0 ? @"yes" : @"yes 3"; 
    NSURL *url = [[NSBundle mainBundle] URLForResource:sound withExtension:@"mp3"]; 

    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; 
    [self.audioPlayer play]; 
} 

注意这绝对与你正在搞的声音变量无关。如上所示,您应该在创建该变量时使用*来指示指针。