2010-03-19 59 views
1

因此,我正在完成一個iPhone應用程序。Objective-C/iPhone中的音頻循環

我已經制定了下面的代碼來播放該文件:

while(![player isPlaying]) { 
    totalSoundDuration = soundDuration + 0.5; //Gives a half second break between sounds 
    sleep(totalSoundDuration); //Don't play next sound until the previous sound has finished 
    [player play]; //Play sound 
    NSLog(@" \n Sound Finished Playing \n"); //Output to console 
} 

出於某種原因,聲音播放一次,然後代碼迴路,它輸出以下內容:

Sound Finished Playing 
Sound Finished Playing 
Sound Finished Playing 
etc... 

這只是我永遠不會重複,我想你們中任何一個可愛的人都無法理解這可能是什麼?

乾杯!

回答

3

我不完全確定你的代碼有什麼問題,它可能是[播放器播放]是一個異步調用,但你永遠循環而不讓播放器真正開始播放或意識到它實際上在播放。我不建議在任何iPhone應用程序中使用sleep,因爲整個模型基於異步事件。

我沒有測試這個代碼,甚至沒有編譯它,但我希望你能從中得到這個想法。

 
- (void) startPlayingAgain:(NSTimer *)timer 
{ 
    AVAudioPlayer *player = timer.userInfo; 

    [player play]; 
} 

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player 
         successfully:(BOOL)flag 
{ 
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5 
          target:self 
          selector:@selector(startPlayingAgain:) 
          userInfo:player 
          repeats:NO]; 
} 

- (void)startPlaying:(NSString *)url 
{ 
    AVAudioPlayer *player = [[AVAudioPlayer alloc] 
           initWithContentsOfURL:url error:NULL]; 

    player.delegate = self; 

    [player play]; 
} 

+0

你的意思是這樣的: - (無效)audioPlayerDidFinishPlaying:(的NSString *)audioPlayer完成:(BOOL *)完成背景:(無效*)上下文{} - 你可以彈出了我一個簡單的例子任何機會,請? :) – 2010-03-19 10:02:57

+0

當然,給我第二個... – 2010-03-19 10:09:01

+0

非常感謝! – 2010-03-19 10:41:45