2013-03-12 83 views
4

我有兩種不同的按鈕按鈕聲音動作。當我按下一個按鈕時,它應該播放一個聲音,當我按下另一個時,它應該停止第一個聲音並播放另一個聲音,我該怎麼做?如何停止AudioToolbox聲音?

感謝,

-(void) onButtonPressAlbina { 
    [soundID2 stop];  
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"albina" ofType:@"m4a"]; 
    SystemSoundID soundID; 
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID); 
    AudioServicesPlaySystemSound (soundID); 
} 

-(void) onButtonPressBalena { 
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"balena" ofType:@"m4a"]; 
    SystemSoundID soundID; 
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID); 
    AudioServicesPlaySystemSound (soundID);  
} 

回答

3

你不能停止的Via「AudioServicesPlaySystemSound」播放聲音,但你可以做的是使用「AVAudioPlayer」代替。

在對象中保留對「AVAudioPlayer」的引用,然後在需要暫停時可以調用"stop"

播放

#import <AudioToolbox/AudioToolbox.h> 
#import <AVFoundation/AVAudioPlayer.h> 
AVAudioPlayer *player; 

// ... 

NSString *path; 
NSError *error; 
path = [[NSBundle mainBundle] pathForResource:@"albina" ofType:@"m4a"]; 
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) 
{  
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error]; 
    player.volume = 0.5f; 
    [player prepareToPlay]; 
    [player setNumberOfLoops:0]; 
    [player play];  
} 

停止

if (player != nil) 
{ 
    if (player.isPlaying == YES) 
    [player stop]; 
} 
+0

非常感謝,它的工作 – Mihai 2013-03-12 20:14:00