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.
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With