AVAudioplayer无法播放。

4

您好,我是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];
}

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


请使用NSLog(@"%@", path);打印输出。请添加一个URL变量并将其记录下来。 - danh
1个回答

28

问题已解决

您在viewDidLoad方法中定义和初始化了AVAudioPlayer。因此,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];
}

1
谢谢,知道有人愿意帮忙总是很好的 :D - haseo98
什么是 pathForResource? - Shikha Sharma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接