使按钮在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?

您的按钮操作方法必须具有以下签名:

-(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映射到按钮来获得更多的创意。

这是您编辑后的答案。希望这有帮助:

-(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)
}

最新更新