我正在创建一个声音板应用程序,一次播放一个声音。我希望 UIButton 能够阻止所有其他声音播放,并在点击时开始播放自己的声音。我有一个 AVAudioPlayer 设置播放所有声音(我点击时更改声音文件网址,因为我一次只想要一个声音播放这不是一个问题)。我想知道如何根据按下的按钮停止所有其他声音并播放声音,但如果单击的按钮是当前正在播放声音的按钮,则该按钮仅停止声音。我知道这可以通过分离音频播放器和触发停止事件来实现,但我想避免复制和粘贴代码并尽可能保持高效,而且我只想要/需要一个音频层。这是我的代码:
- (IBAction)play {
if (audioPlayer.playing == NO) {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/k.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
[audioPlayer release];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
AVAudioSession *audiosession = [AVAudioSession sharedInstance];
[audiosession setCategory:AVAudioSessionCategoryAmbient error:nil];
[audioPlayer play];
[start setTitle:@"Stop" forState:UIControlStateNormal];
}
else
if (audioPlayer.playing == YES) {
[audioPlayer stop];
[start setTitle:@"Start" forState:UIControlStateNormal];
}
}
- (IBAction)play2 {
if (audioPlayer.playing == NO) {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/chicken.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
[audioPlayer release];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
AVAudioSession *audiosession = [AVAudioSession sharedInstance];
[audiosession setCategory:AVAudioSessionCategoryAmbient error:nil];
[audioPlayer play];
[start2 setTitle:@"Stop" forState:UIControlStateNormal];
} else
if (audioPlayer.playing == YES) {
[audioPlayer stop];
[start2 setTitle:@"Start" forState:UIControlStateNormal];
}
}
任何帮助表示赞赏。先感谢您!
2 回答
就这样做吧
并在每次点击时调用此功能..
单击按钮时,停止播放音频播放器并分配新的歌曲 URL,然后在单击按钮播放歌曲时播放 it.Write 此代码。