2013年8月22日 星期四

AVAudioPlayer 在使用 ARC 的情況下無法播放音效

- (IBAction)startMusic:(id)sender {

    NSError *error = nil;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Harlem_Shake" ofType:@"mp3"];
    NSURL *fileURL = [NSURL fileURLWithPath:path];
    AVAudioPlayer *playMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
    
    playMusic.delegate = self;
    [playMusic play];
}

上面 code 打完後超納悶,

一個字一個字檢查了十來次,

明明就沒有打錯,音效卻死不出來。


最後終於找到了答案:

ARC 機制會自動新增一個 AVAudioPlayer 的 release,

這個 release 會在離開它所在的 method 後隨即被 dealloc 掉。

所以上面那段 code 執行到 [music play]; 時,

音樂雖然開始播了,

但下一秒 music 物件立即被 dealloc 掉了,

所以不會有任何音效播出。


解決方法將 AVAudioPlayer 物件宣告在 .h 檔,

並加入 strong 型別
@property (strong, nonatomic) AVAudioPlayer *playMusic;
就解決了