繁体   English   中英

AVAudioplayer没有播放

[英]AVAudioplayer not playing

嗨,我是ios开发的新手,我正在尝试编写一个基本的应用程序。 我希望有声音,更具体地说是“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];
}

然而,这导致在模拟器和物理设备中都没有播放声音。 如果我能得到一些帮助,我将不胜感激。

问题解决了

您已在viewDidLoad方法中定义并初始化了AVAudioPalyer。 因此,audioPlayer对象的生命周期仅限于viewDidLoad方法。 该对象在方法结束时死亡,因此音频将无法播放。 您必须保留该对象,直到它结束播放音频。

全局定义avPlayer,

@property(nonatomic, strong) AVAudioPlayer *theAudio;

在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