【发布时间】:2024-01-16 12:38:01
【问题描述】:
当我按下一个按钮,然后再按下另一个按钮时,声音会重叠。我该如何解决这个问题,以便在按下另一个声音时停止第一个声音?
- (void)playOnce:(NSString *)aSound {
NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio setDelegate: self];
[theAudio setNumberOfLoops:0];
[theAudio setVolume:1.0];
[theAudio play];
}
- (void)playLooped:(NSString *)aSound {
NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio setDelegate: self];
// loop indefinitely
[theAudio setNumberOfLoops:-1];
[theAudio setVolume:1.0];
[theAudio play];
[theAudio release];
}
【问题讨论】:
-
你需要真正提出一个问题。
-
我的问题是,当我点击一个按钮时,它会播放声音,然后我点击另一个按钮,它们会重叠
-
您可以执行以下任一操作: 1. 当按钮单击时,检查 AVaudioplayer 是否仍在播放。如果是,你可以忽略它而不做任何事情,或者 2 你可以停止它然后播放新的声音。
-
- (void)playOnce:(NSString *)aSound;
-
- (IBAction) beatButton50 { [self playOnce:@"racecars"]; }