您好我是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];
}
然而,这导致在模拟器和物理设备中都没有播放声音。如果我能得到一些帮助,我将不胜感激。
答案 0 :(得分:28)
您已在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];
}