簡體   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