2012-01-02 101 views
1

我以前的代码为AVAudioPlayer - 暂停按钮

- (void) playaudio: (id) sender 
{ 
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Theme" 
               ofType:@"mp3"]; 
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath]; 

    self.audioPlayer = [[AVAudioPlayer alloc] 
       initWithContentsOfURL:fileURL error:nil]; 

    self.audioPlayer.currentTime = 0; 
    [self.audioPlayer play]; 
} 

- (void)pause: (id)sender 

{ 
    [audioPlayer pause]; 

} 

- (void)stop: (id)sender 

{ 

    [audioPlayer stop]; 

} 

在上面的代码暂停按钮被用作停止按钮,而不是停顿在那里本来是要恢复的音频文件。

现在我已经添加了简单的声明到我的代码它在某种程度上工作,但仍然没有达到我的期望。

现在发生的情况是,当您播放音频文件并单击暂停按钮时什么也没有发生,但是当您点击停止按钮时,它将停止播放音频文件,然后当您按下暂停按钮时,它将恢复音频文件按停止按钮停止。为什么当你按下停止按钮时只有暂停按钮功能,但在此之前没有。我不明白这是为什么?

任何想法,为什么发生这种情况

- (void)pause: (id)sender 

{ 

    [audioPlayer pause];  
    [audioPlayer prepareToPlay]; 
    [audioPlayer play]; 


} 


- (void) stop: (id) sender 

{ 
    [audioPlayer stop]; 

} 

如果任何人有任何的想法,为什么发生这种情况。将感谢帮助。

在此先感谢。

回答

4

每次播放时都不应该重新创建音频文件。这里是你如何做到这一点:

- (void) playaudio: (id) sender 
{ 
    if(self.audioPlayer == nil) { 
     NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Theme" 
               ofType:@"mp3"]; 
     NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath]; 

     self.audioPlayer = [[AVAudioPlayer alloc] 
       initWithContentsOfURL:fileURL error:nil]; 

     self.audioPlayer.currentTime = 0; //this could be outside the if if you want it to start over when they hit play 
    } 
    [self.audioPlayer play]; 
} 

- (void)pause: (id)sender 

{ 
    if([audioPlayer isPlaying]){ 
     [audioPlayer pause]; 
    } else { 
     [audioPlayer play]; 
    } 

} 

- (void)stop: (id)sender 

{ 

    [audioPlayer stop]; 

} 
+0

Bingo .. + 1 ..享受编码.. :) – 2013-04-27 06:33:41