在 iOS 中以编程方式使按钮播放声音
Posted
技术标签:
【中文标题】在 iOS 中以编程方式使按钮播放声音【英文标题】:Making a button programmatically play a sound in iOS 【发布时间】:2014-03-05 06:55:02 【问题描述】:我想创建一个按钮,让它在被触摸时播放声音。到目前为止,我可以制作按钮,但我无法让它播放声音。这是我所拥有的:
//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?
【问题讨论】:
如果您已解决此问题,请接受正确答案以帮助遇到相同问题的其他人。 @BhushanUparkar 同上 【参考方案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 映射到按钮来获得更多创意。
【讨论】:
哎呀!您在我创建答案时发布了答案:)【参考方案2】:这是您编辑后的答案。希望这会有所帮助:
-(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)
【讨论】:
以上是关于在 iOS 中以编程方式使按钮播放声音的主要内容,如果未能解决你的问题,请参考以下文章