2014-03-05 74 views
1

我想創建一個按鈕,並在觸摸時使其播放聲音。到目前爲止,我可以製作這個按鈕,但是我很難讓它播放聲音。以下是我的:在iOS中以編程方式製作按鈕播放聲音

//loads wav file into SoundID 
NSURL *buttonURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"medic_taunts01" ofType:@"wav"]]; 
AudioServicesCreateSystemSoundID((__bridge CFURLRef)buttonURL, &SoundID); 

//creates button 
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[button setTitle:@"Show View" forState:UIControlStateNormal]; 
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); 
[scrollview addSubview:button] 

//this line is the problem 
[button addTarget:self action:@selector(AudioServicesPlaySystemSound((SoundID)) forControlEvents:UIControlEventTouchDown]; 

由於某些原因,xcode不會讓我直接從按鈕單擊播放聲音。我怎樣才能讓觸摸按鈕播放SoundID?

+1

如果你已經解決這個問題,然後接受正確的答案,以幫助其他人有同樣的問題。 – BhushanVU

+0

@BhushanUparkar同上 – madLokesh

回答

1

您的按鈕操作方法必須具有以下簽名:

-(void)buttonActionMethod:(id)inSender 

這意味着你不能直接調用的系統方法。對於你正在嘗試做的,我建議這個方法:

//loads wav file into SoundID 
NSURL *buttonURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"medic_taunts01" ofType:@"wav"]]; 
SystemSoundID soundID 
AudioServicesCreateSystemSoundID((__bridge CFURLRef)buttonURL, &soundID); 
self.SoundID = soundID; 

//creates button 
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[button setTitle:@"Show View" forState:UIControlStateNormal]; 
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); 
[scrollview addSubview:button] 

//this line is the problem 
[button addTarget:self action:@selector(playButtonSound:) forControlEvents:UIControlEventTouchDown]; 

SoundID一個屬性(我相信你知道如何使那些)的轉換。然後定義這個方法:

-(void)playButtonSound:(id)inSender { 
    AudioServicesPlaySystemSound(self.SoundID); 
} 

當然,如果你有一個以上的按鈕,每一個不同的聲音,你將需要獲得更多一點創意在這裏與測繪聲音標識的按鈕。

+0

哎呀!你發佈你的答案,而我正在創建一個:) – madLokesh

+0

謝謝!這工作就像一個魅力:) – Quikdart

0

這是你編輯的答案。希望這有助於:

-(void)viewDidLoad { 

     NSURL *buttonURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"medic_taunts01" ofType:@"wav"]]; 
     AudioServicesCreateSystemSoundID((__bridge CFURLRef)buttonURL, &SoundID); 

     //creates button 
     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     [button setTitle:@"Show View" forState:UIControlStateNormal]; 
     button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); 
     [scrollview addSubview:button] 

     //this line was causing problem 
     [button addTarget:self action:@selector(playSound:) forControlEvents:UIControlEventTouchDown]; 


} 


-(void)playSound:(id)sender{ 

     AudioServicesPlaySystemSound((SoundID) 

    }