我正在創建一次播放一個聲音的聲卡應用程序。我希望UIButton能夠阻止所有其他聲音播放,並在點擊時開始播放自己的聲音。我有一臺AVAudioPlayer設置爲播放所有聲音(單擊時更改聲音文件的URL,因爲我一次只想播放一個聲音並不是問題)。我想知道如何停止所有其他聲音並按下按鈕播放聲音,但如果點擊的按鈕是當前正在播放聲音的按鈕,則該按鈕僅會停止聲音。我知道這是可以實現的,通過分開音頻播放器和觸發停止事件,但我想避免複製和粘貼代碼,並保持儘可能高效,再加上我只想/需要一個音頻播放器。這裏是我的代碼:觸發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];
}
}
任何幫助表示讚賞。先謝謝你!