2011-04-26 84 views
0

我有一個聲音循環,它是一個矩形按鈕,一旦用戶按下按鈕,聲音循環播放。我想要它,所以一旦用戶再次按下相同的按鈕,聲音停止播放。如何停止聲音 - 可可觸摸

這是代碼

- (IBAction)threeSound:(id)sender; { 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"wav"]; 
    if (threeAudio) [threeAudio release]; 
    NSError *error = nil; 
    threeAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error]; 
    if (error) 
     NSLog(@"%@",[error localizedDescription]); 
    threeAudio.numberOfLoops = -1; 
    threeAudio.delegate = self; 
    [threeAudio play]; 

} 

感謝

回答

1

漂亮的直線前進......

- (IBAction)threeSound:(id)sender; { 
    if (threeAudio && threeAudio.playing) { 
     [threeAudio stop]; 
     [threeAudio release]; 
     threeAudio = nil; 
     return; 
    }   
    NSString *path = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"wav"]; 
    if (threeAudio) [threeAudio release]; 
    NSError *error = nil; 
    threeAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error]; 
    if (error) 
     NSLog(@"%@",[error localizedDescription]); 
    threeAudio.numberOfLoops = -1; 
    threeAudio.delegate = self; 
    [threeAudio play]; 

} 
+0

此代碼還假定正在爲這兩個事件調用threeSound。 – slycrel 2011-04-27 00:07:12

+0

他提到「再次按下相同的按鈕」,所以我認爲這是正確的。 – NWCoder 2011-04-27 00:10:47

+0

對不起,我同意你的看法,只是爲了防止別人出現。 =) – slycrel 2011-04-27 06:29:27

0

你應該 分開這兩個進程進入這個

`- (void)initSound { 
NSString *path = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"wav"]; 
NSError *error = nil; 
    threeAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error]; 
    if (error) 
     NSLog(@"%@",[error localizedDescription]); 
    threeAudio.numberOfLoops = -1; 
    threeAudio.delegate = self; 
    [threeAudio prepareToPlay]; 
    [threeAudio play]; 
} 

-(IBAction)threeSound:(id)sender:(UIButton *)sender{ 
    if (sender.selected) { 
    [threeAudio pause]; 
    } else { 
    threeAudio.currentTime = 0;  
     [threeAudio play]; 
    } 
    sender.selected = !sender.selected; 
}` 

注意initSound需要在某些時候被調用,如果你想開始按鈕的聲音只..然後在的IBAction爲

這就是我的建議的beggining添加

if (!threeAudio) { 
     [self initSound]; 
} 

;)

+0

這會使代碼更加複雜,除非您停止/從其他位置(而不僅僅是按鈕)啓動聲音,在這種情況下,代碼會變得更簡單。但任何一種方式都可行 – 2011-08-11 06:41:10