【问题标题】:Making a button programmatically play a sound in iOS在 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 同上

标签: ios objective-c audio uikit


【解决方案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)

  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 2011-03-23
    • 2013-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    相关资源
    最近更新 更多