简体   繁体   中英

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.

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM