简体   繁体   English

AVAudioplayer没有播放

[英]AVAudioplayer not playing

Hi i'm new to ios development and am attempting to write a basic application. 嗨,我是ios开发的新手,我正在尝试编写一个基本的应用程序。 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: 我希望有声音,更具体地说是“sound.mp3”从发布开始播放,因此我将以下代码包含在我的程序中:

   - (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. 您已在viewDidLoad方法中定义并初始化了AVAudioPalyer。 Therefore the life of the audioPlayer object is limited to viewDidLoad method. 因此,audioPlayer对象的生命周期仅限于viewDidLoad方法。 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, 全局定义avPlayer,

@property(nonatomic, strong) AVAudioPlayer *theAudio;

in viewDidLoad, 在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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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