2013-06-13 102 views
0

我需要打開視圖後自動播放音頻,並有一個按鈕來控制播放/暫停事件。我聽說它有一個prepareToPlay按鈕來控制音頻,但它不能自動播放音頻。 這裏是我的代碼:是否可以使用按鈕自動播放音頻和播放/暫停?

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
            pathForResource:@"track8" 
            ofType:@"mp3"]]; 
NSError *error; 
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 

[audioPlayer prepareToPlay]; 

和按鈕:

-(IBAction)playPauseButtonPress:(id)sender{ 

if (self.isPlaying) { 

    [self.audioPlayer pause]; 

    self.isPlaying = NO; 

}else { 
    [self.audioPlayer play]; 

    self.isPlaying = YES; 


} 
} 

是否可以自動播放音頻和播放/與按鈕暫停?怎麼樣?

回答

0
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
           pathForResource:@"track8" 
           ofType:@"mp3"]]; 
NSError *error; 
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 

[audioPlayer prepareToPlay]; 

有方法play可用於播放它。你只需要添加以下行:

[audioPlayer play]; 

請檢查AVAudioPlayer documentation

發揮> Calling this method implicitly calls the prepareToPlay method if the audio player is not already prepared to play.

prepareToPlay>Calling this method preloads buffers and acquires the audio hardware needed for playback, which minimizes the lag between calling the play method and the start of sound output.Calling the stop method, or allowing a sound to finish playing, undoes this setup.

有沒有像你不能暫停音頻如果您使用play而不是prepareToPlay

希望這有助於

+0

是的,有,但是如果我使用「玩」的方法,將「prepareToPlay」方法不爲什麼要使用'prepareToPlay'工作 – Matin

+0

?如果您直接使用'play',它將在啓動時播放,即使您可以使用暫停/播放。 –

+0

我混淆了這兩種方法,非常感謝 – Matin

相關問題