2011-02-15 16 views
1

我有一個UAViewController的子類,用AVAudioPlayer在後臺播放歌曲。在我的viewDidLoad方法中,我有以下代碼:在UIViewController中使用AVAudioPlayer

[super viewDidLoad]; 

... 

[NSTimer scheduledTimerWithInterval: 0.03 target: self selector: @selector(gameLoop) userInfo: nil repeats: YES]; 

NSString *path = @"path-to-song"; 
self->audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath: path] error: NULL]; 
audioPlayer.delegate = self; 
audioPlayer.numberOfLoops = - 1; 
[audioPlayer play]; 

gameLoop是一種包含遊戲核心邏輯的方法。當我在測試設備上運行應用程序時,音頻播放,但它似乎被凍結,並且gameLoop無法正常運行。如果我刪除了所有的AVAudioPlayer代碼,遊戲就會正常工作。這似乎有一些線程問題,我不知道。有任何想法嗎?

+0

音頻文件的格式是什麼? (只是檢查它不是一個44Mhz的AIFF文件或非常高比特率的MP3或任何東西。) – 2011-02-15 22:25:47

+0

爲什麼這會有所作爲?音頻播放良好... – 2011-02-16 00:30:12

回答

2

請嘗試移動AVAudioPlayer的代碼放到一個方法,並運行它在後臺線程後調用像這樣:

- (void)playSong:(NSURL*)atURL 
{ 
    self->audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: atURL error: NULL]; 
    audioPlayer.delegate = self; 
    audioPlayer.numberOfLoops = - 1; 
    [audioPlayer play]; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    ... 

    NSURL* url = [NSURL fileURLWithPath: @"path-to-song"] 
    [self performSelectorInBackground: @selector(playSong:) withObject: url]; 
} 
0

刪除計時器重複:Yes(是)重複:NO.May是其problem.Because你gameLoop方法將每0.3秒

+1

這就是意圖 - 因此遊戲**循環**;) – 2011-02-16 09:32:17