ios – AVAudioplayer没有播放
发布时间:2020-12-14 19:00:52 所属栏目:百科 来源:网络整理
导读:嗨,我是ios开发的新手,我正在尝试编写一个基本的应用程序.我希望有声音,更具体地说是“sound.mp3”从发布开始播放,因此我将以下代码包含在我的程序中: - (void)viewDidLoad{[super viewDidLoad];[UIView animateWithDuration:1.5 animations:^{[self.view s
嗨,我是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]; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |