当前位置: 动力学知识库 > 问答 > 编程问答 >

objective c - I am writing a pretty simple iPhone app that will play a sound depending on which button is pressed

问题描述:

A... as I learn Objective C.

There will be close to 20 button on a view at a time... :)

If I use a if/else loop for each button touched, it works great but I consider that to be inelegant and just plain cumbersome.

SO, I am using the button.tag to allow me to assign a number to each button then evaluate each button based on the .tag property.

As I mentioned before, works great with if/else if loops.

But I want to change the tag to a string and then nest it within a NSURL to play a sound. Each button will generate a new tag and consequently a new sound.

As reported by the debugger, I am getting Not a CFSTRING and 'out of bounds' messages and upon stepping through, crashes. Fun, but not blue screen.

Here is the code in question. I humbly request of the Objective C gurus to lend some insight!

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];

*/

Thanks,

Neil

网友答案:

I would create an array with all 20 file paths in it, then i would use the tag to index the array.

网友答案:

It almost sounds like you're programming behaviour in your buttons.

Why don't you just assign each button to a different IBOutlet/callback method? You won't need any if/else statements at all.

网友答案:

On your IBActions, add something like this:

SystemSoundID theSound; 
NSString *pathToSound;

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

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

Then add this to your .h file and the the AudioToolbox.framework to your project:

#import <AudioToolbox/AudioToolbox.h>

Worked like a charm for me. Hope this helps.

网友答案:

Thanks! I got the code to work and I used the button.tag. Then, I named each sound file against the tag number.. So, tag 1 = 1.aif, tag 2=2.aif etc... I used a paper chart to get started then off to the races. THe issue I had was how to get the button.tag as a string and I struggled until I figured it out: -(IBAction)buttonPressed:(id)sender; int soundTag = [sender tag]; soundPick = [[NSString alloc] initWithFormat: @"%d", soundTag]; Then took soundPick and stuck in the appropriate location in NSURL.. Thanks!

分享给朋友:
您可能感兴趣的文章:
随机阅读: