Monday, May 16, 2011

How to add Muiltiple Sound buttons...

Assuming you have the following sounds included in your apps.

sound1.wav
sound2.wav
sound3.wav
sound4.wav
sound5.wav
sound6.wav
sound7.wav

.h File for View

#import <UIKit/UIKit.h>
#import<AVFoundation/AVAudioPlayer.h>

@interface buttonSoundViewController : UIViewController <AVAudioPlayerDelegate> {
    }
-(IBAction) button1:(id)sender;
-(IBAction) button2:(id)sender;
-(IBAction) button3:(id)sender;
-(IBAction) button4:(id)sender;
-(IBAction) button5:(id)sender;
-(IBAction) button6:(id)sender;
-(IBAction) button7:(id)sender;

@end

.M File

-(IBAction) button1:(id)sender{
   
    NSString *path = [[NSBundle mainBundle] pathForResource:@"sound1" ofType:@"wav"];
    AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
   
    theAudio.delegate=self;
    [theAudio play];
       
    }

-(IBAction) button2:(id)sender{
   
    NSString *path = [[NSBundle mainBundle] pathForResource:@"sound2" ofType:@"wav"];
    AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
   
    theAudio.delegate=self;
    [theAudio play];
   
}

-(IBAction) button3:(id)sender{
   
    NSString *path = [[NSBundle mainBundle] pathForResource:@"sound3" ofType:@"wav"];
    AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
   
    theAudio.delegate=self;
    [theAudio play];
   
}

-(IBAction) button4:(id)sender{
   
    NSString *path = [[NSBundle mainBundle] pathForResource:@"sound4" ofType:@"wav"];
    AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
   
    theAudio.delegate=self;
    [theAudio play];
   
}

-(IBAction) button5:(id)sender{
   
    NSString *path = [[NSBundle mainBundle] pathForResource:@"sound5" ofType:@"wav"];
    AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
   
    theAudio.delegate=self;
    [theAudio play];
   
}

-(IBAction) button6:(id)sender{
   
    NSString *path = [[NSBundle mainBundle] pathForResource:@"sound6" ofType:@"wav"];
    AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
   
    theAudio.delegate=self;
    [theAudio play];
   
}

-(IBAction) button7:(id)sender{
   
    NSString *path = [[NSBundle mainBundle] pathForResource:@"sound7" ofType:@"wav"];
    AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
   
    theAudio.delegate=self;
    [theAudio play];
   
}


In Interface building you have to link each button the the right function for this to work.

Note: The first time you press a button there is a 3 second delay. After that every button you press works. please e-mail timbojill@gmail.com.

No comments:

Post a Comment