2012-09-25 198 views
-1

我面臨一個很奇怪的問題,我的要求是發揮按鈕單擊聲音,這是我的代碼:播放聲音單擊

- (void)viewDidLoad 
{ 
    [super viewDidLoad];  
    NSString *path=[[NSBundle mainBundle] pathForResource:@"button-3" ofType:@"mp3"]; 
    tapSound=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]]; 
    [tapSound prepareToPlay]; 
    tapSound.delegate=self; 

    //creating the button in view did load and button is declared in .h 
    btn=[UIButton buttonWithType:UIButtonTypeCustom]; 
    btn.frame=CGRectMake(x, y, 58,58); 
    [btn addTarget:self action:@selector(btnClkd:) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:btn]; 
} 

//click method 
-(void)btnClkd:(UIButton*)sender 
{ 
[tapSound play]; 
} 

但是當我運行的代碼,然後點擊按鈕我的應用程序得到墜毀,得到這個錯誤:「終止應用程序由於未捕獲的異常‘NSInvalidArgumentException’,原因是:‘ - [UIButton的發揮]:無法識別的選擇發送到實例0x758c790’」

但是如果我播放聲音的任何地方否則,但不是在按鈕的點擊,然後它沒有任何問題發揮。我不知道爲什麼會發生這種情況?請幫我

+0

通過分配它來嘗試按鈕。 我不確定,但只是試試這樣。 – Deepak

回答

2

這樣做:

-(void)btnClkd:(UIButton*)sender 
{ 
    NSString *path=[[NSBundle mainBundle] pathForResource:@"button-3" ofType:@"mp3"]; 
    tapSound = nil; 
    tapSound=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]]; 
    [tapSound prepareToPlay]; 
    tapSound.delegate=self; 
    [tapSound play]; 
} 
+0

我知道它會工作,但爲什麼當我們在視圖中定義AVAudioPlayer對象的時候給出了一個問題? –

0

試試這一個。添加在你的.h文件中

.h file 



     #import <AVFoundation/AVFoundation.h> 
      #import <AudioUnit/AudioUnit.h> 


     AVAudioPlayer *player1; 

     @property(nonatomic ,retain)AVAudioPlayer *player1; 

in your .m file 




@synthesize player1; 



    - (void)viewDidLoad 
     { 
      [super viewDidLoad];  

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
      NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"button-3" ofType:@"mp3"];  
      NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];  
      AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];  
      [fileURL release]; 
      self.player1 = audioPlayer;  
      [audioPlayer release]; 
      [self.player1 prepareToPlay]; 
      [self.player1 setDelegate:self]; 
      [pool release]; 

      //creating the button in view did load and button is declared in .h 
      btn=[UIButton buttonWithType:UIButtonTypeCustom]; 
      btn.frame=CGRectMake(x, y, 58,58); 
      [btn addTarget:self action:@selector(btnClkd:) forControlEvents:UIControlEventTouchUpInside]; 
      [self.view addSubview:btn]; 
     } 




    -(void)btnClkd:(UIButton*)sender {    

      [self.player1 play]; 

    } 
+0

哎維卡斯,它也沒有工作 –

+0

它的工作..我的應用 –

+0

我想它在模擬器和它不工作 –