2014-09-22 67 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]; 
} 

注意這絕對與你正在搞的聲音變量無關。如上所示,您應該在創建該變量時使用*來指示指針。