我想创建一个按钮,让它在触摸时播放声音。到目前为止,我可以制作按钮,但我无法播放声音。这就是我所拥有的:
//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?
答案 0 :(得分: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);
}
当然,如果您有多个按钮,每个按钮都有不同的声音,那么您需要在此处获得更多创意,并将声音ID映射到按钮。
答案 1 :(得分: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)
}