Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVAudioplayer not playing

Hi i'm new to ios development and am attempting to write a basic application. I would like there to be sound, more specifically "sound.mp3" playing from launch and as such i have included the following code into my program:

   - (void)viewDidLoad
{
[super viewDidLoad];
[UIView animateWithDuration:1.5 animations:^{[self.view setBackgroundColor:[UIColor redColor]];}];
[UIView animateWithDuration:0.2 animations:^{title.alpha = 0.45;}];
//audio
NSString *path = [[NSBundle mainBundle]pathForResource:@"sound" ofType:@"mp3"];
AVAudioPlayer *theAudio = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio play];
}

This however results in no sound being played in neither the simulator nor the physical device. It would be greatly appreciated if i could receive some assistance.

like image 551
haseo98 Avatar asked Nov 28 '22 14:11

haseo98


1 Answers

Problem Solved

You have defined and initialised the AVAudioPalyer inside viewDidLoad method. Therefore the life of the audioPlayer object is limited to viewDidLoad method. The object dies at the end of the method, and the audio will not play because of that. You have to retain the object till it ends playing the audio.

Define the avPlayer globally,

@property(nonatomic, strong) AVAudioPlayer *theAudio;

in viewDidLoad,

- (void)viewDidLoad
{
[super viewDidLoad];
[UIView animateWithDuration:1.5 animations:^{[self.view setBackgroundColor:[UIColor redColor]];}];
[UIView animateWithDuration:0.2 animations:^{title.alpha = 0.45;}];
//audio
NSString *path = [[NSBundle mainBundle]pathForResource:@"sound" ofType:@"mp3"];
self.theAudio = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[self.theAudio play];
}
like image 166
Thilina Chamath Hewagama Avatar answered Dec 06 '22 00:12

Thilina Chamath Hewagama