我正在写一个非常简单的iPhone应用程序,根据按下哪个按钮播放声音

时间:2010-01-30 08:02:24

标签: iphone objective-c

A ......当我学习目标C.

一次一个视图上将有近20个按钮...... :)

如果我为触摸的每个按钮使用if / else循环,它效果很好,但我认为它不够优雅而且简单笨重。

所以,我使用button.tag来允许我为每个按钮分配一个数字,然后根据.tag属性评估每个按钮。
正如我之前提到的,if / else if循环很好用。

但是我想将标签更改为字符串,然后将其嵌套在NSURL中以播放声音。每个按钮都会生成一个新标签,从而产生新的声音。

正如调试器报告的那样,我得到的不是CFSTRING和'越界'消息,并且在单步执行时崩溃。有趣,但不是蓝屏。

以下是相关代码。我谦卑地要求Objective C gurus提供一些见解!

int soundNumber = [sender tag];

//soundPick = [NSString stringWithFormat:@"%d", soundNumber]; //remmed out as an alternative try
NSString *soundPick = [[NSNumber numberWithInt:soundNumber] stringValue];

NSURL *aSoundURL = [NSURL fileURLWithPath:[mainBundle pathForResource:soundPick ofType:@"aif"]];   
playSound = [[AVAudioPlayer alloc] initWithContentsOfURL:aSoundURL error:&error];
if (!playSound) {
    NSLog(@"no Sound for that button: %@", [error localizedDescription]); 
} 
[playSound play];

*/

谢谢,

尼尔

4 个答案:

答案 0 :(得分:1)

我会创建一个包含所有20个文件路径的数组,然后我会使用该标记来索引数组。

答案 1 :(得分:0)

这几乎听起来像是你按钮中的编程行为。

为什么不将每个按钮分配给不同的IBOutlet /回调方法?你根本不需要任何if / else语句。

答案 2 :(得分:0)

在您的IBActions上,添加以下内容:

SystemSoundID theSound; 
NSString *pathToSound;

pathToSound = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"<filename>" ofType:@"<filetype>"] isDirectory:NO];

AudioServicesCreateSystemSoundID((CFURLRef)pathToSound, &theSound);
AudioServicesPlaySystemSound (theSound);

然后将此添加到您的.h文件和项目的AudioToolbox.framework:

#import <AudioToolbox/AudioToolbox.h>

对我来说就像一个魅力。希望这会有所帮助。

答案 3 :(得分:-1)

谢谢!我得到了代码,我使用了button.tag。然后,我将每个声音文件命名为标签号。所以,标签1 = 1.aif,标签2 = 2.aif等...我用纸质图表开始然后关闭比赛。我遇到的问题是如何将button.tag作为一个字符串,我一直在努力直到我想出来: - (IBAction)buttonPressed:(id)sender; int soundTag = [sender tag]; soundPick = [[NSString alloc] initWithFormat:@“%d”,soundTag];然后拿了soundPick并卡在NSURL的适当位置..谢谢!