2012-05-01 205 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成为该类的一个实例变量。