Steven07 Steven07 - 5 months ago 8
Objective-C Question

playing sound and changing image in UIImageView when button is pressed

As the title describes I've been able to add sound when button is pressed, but I was wondering if there was a way to also add an image change to the main UIImageView when the same button is pressed. Is there any way to stick the picture code in where the "playFaceOfAudioType" method is presented?

Here's my code so far:

#import "FourthViewController.h"

@interface FourthViewController ()

@end

@implementation FourthViewController

@synthesize audioPlayer;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}

- (IBAction)facesAudioAction:(id)sender {
UIButton *btn=(UIButton *)sender;
[self playFaceAudioOfType:btn.tag];//Tag for button is set on the xib..

}




-(void)playFaceAudioOfType:(int)type{

[self stopAudio];


NSString *sound=@"";

switch (type) {
case 1:
sound=@"1";
break;

case 2:
sound=@"2";
break;

case 3:
sound=@"3";
break;

case 4:
sound=@"4";
break;

case 5:
sound=@"5";
break;

default:
break;
}


NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:sound
ofType:@"mp3"]];



NSError *error;
if(url){
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];



if (error)
{
NSLog(@"Error in audioPlayer: %@",
[error localizedDescription]);
} else {
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
}

[audioPlayer play];
}


}




-(void)stopAudio{

if(audioPlayer && [audioPlayer isPlaying]){
[audioPlayer stop];
audioPlayer=nil;
}


}



- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end


I understand from looking around that usually this is done by doing an if / else if type of approach but was wondering if it was possible to include it along with the switch statement bit.

Answer

You can use either facesAudioAction or playFaceOfAudioType method for changing image.

Also, you can get rid off switch statement with;

NSString *sound = [NSString stringWithFormat:@"%d", type];

You can set image like this;

NSString *imageName = [NSString stringWithFormat:@"%d.jpg", type];
yourImageView.image = [UIImage imageNamed:imageName];
Comments