2012-05-01 197 views
0

(使用AVFoundation.framework)背景音樂

#import "AVFoundation/AVFoundation.h" 

所以我有一個問題,我第一次在我的課的init方法試過這個代碼(也就是第一次加載一個)

NSString* soundFilePath = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"]; 
NSURL* soundFileURL = [NSURL fileURLWithPath:soundFilePath]; 
AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil]; 
player.numberOfLoops=-1; 
[player play]; 

但它沒有工作,比我決定做它線程: 在init方法:

[NSThread detachNewThreadSelector:@selector(playMusic) toTarget:self withObject:nil]; 

和方法ITSE lf:

-(void) playMusic { 
    NSString* soundFilePath = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"]; 
    NSURL* soundFileURL = [NSURL fileURLWithPath:soundFilePath]; 
    AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil]; 
    player.numberOfLoops=-1; 
    [player play]; 
} 

它當然是在* .h文件中聲明的。它也沒有工作。

我試圖調試,線

} 
playMusic方法的文件被播放爲2或3秒,然後停止的

。沒有調試就不會播放。問題是什麼?

+0

使AVAudioPlayer成爲 – Felix

+0

omg類的一個實例變量o_O 謝謝)) – Alexander

回答

2

AVAudioPlayer將立即解除分配。您需要保留播放器。 因此,讓AVAudioPlayer成爲該類的一個實例變量。