AVAudioplayer not playing

Hi, I am new to ios development and trying to write a main application. I would like it to sound, more specifically "sound.mp3", playing from the moment it was launched, and therefore I included the following code in 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 leads to the fact that the sound is not reproduced either in the simulator or in the physical device. It would be very helpful if I could get some help.

+4
source share
1 answer

Solution

You have defined and initialized the AVAudioPalyer method inside viewDidLoad. Therefore, the life of an audioPlayer is limited by the viewDidLoad method. The object dies at the end of the method, and because of this, the sound will not play. You must save the object until it finishes playing the audio.

Define 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]; } 
+28
source

Source: https://habr.com/ru/post/1479455/


All Articles