2011-04-26 172 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