通过多个按钮播放多个音频文件

时间:2014-03-05 16:48:26

标签: ios objective-c audio

我正在尝试使用音板应用,我需要在视图控制器上使用超过50个按钮(每个声音一个)。此外,我想完全以编程方式制作按钮(和音频播放器代码),因为在故事板和.h / .m文件之间切换是很烦人的。我没有复制和粘贴相同的按钮代码50次,而是使用这个for循环为我制作按钮:

NSUInteger i;
int xCoord=0;
int yCoord=0;
int buttonWidth=100;
int buttonHeight=50;
int buffer = 10;
for (i = 1; i <= 100; i++)
{
    UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
    aButton.frame     = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight );
    [aButton addTarget:self action:@selector(playAudioMethod) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:aButton];

    yCoord += buttonHeight + buffer;
}
[scrollView setContentSize:CGSizeMake(700, yCoord)];

按钮点击事件选择器中的playAudioMethod只播放一个声音。怎么会有50个声音,每个声音对应一个单独的按钮?对不起,如果这是一个非常基本的问题,我仍然在学习目标C.谢谢!

编辑:

这是playAudioMethod:

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

它基本上只播放SoundID属性,我通过这个传递声音文件:

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

2 个答案:

答案 0 :(得分:0)

playAudioMethod有一个参数,即sendersender是生成消息的按钮。

- (void)playAudioMethod:(id)sender
{
    UIButton *button = (UIButton *)sender;
    switch (button.tag)
    {
           //....
    }
}

您可以使用按钮的tag属性来存储值,例如,您可以存储一个允许您识别playAudioMethod中的按钮的整数,或者您可以直接存储该名称。音频资源。

答案 1 :(得分:0)

相关问题