* これは私の最初のスタック オーバーフローの質問です。
シンプルなサウンドボードアプリを作ろうとしています。xCode 4.1 (iOS 6.1.2) で AVAudioPlayer を取得して、再生するサウンド ファイルの場所を更新するのに問題があります。複数のオーディオ プレーヤー (audioPlayer2、audioPlayer3 など) を持たないようにしたかったので、同じオーディオ プレーヤーを使用しようとしていますが、代わりに、サウンド ファイルの場所を更新します。一度に 1 つのサウンドだけを再生したいので、複数のサウンドは明らかに問題ではありません。これが私のコードです:
- (IBAction)play {
if (audioPlayer.playing == NO) {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/k.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
//I added the next two lines to allow me to play AVAudio with MPiPodPlayer (which I found on this site, too) simultaneously.
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 = [[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];
clicked = 1;
clicked2 = 0;
} else
if (audioPlayer.playing == YES) {
[audioPlayer stop];
[start2 setTitle:@"Start" forState:UIControlStateNormal];
clicked = 0;
}
}
私の IBActions は UIButtons にリンクされており、'start's は UIButton 参照です。「開始」をクリックするたびに「k.mp3」が正常に再生されますが、その後「開始 2」をクリックすると、チキン ファイルではなく「k.mp3」ファイルの再生が開始されます。最初にクリックしたボタンに、URL が設定されます。これは私の最初の iPhone OS アプリケーション プロジェクトなので、おそらくいくつかの恥ずかしいコーディング ミスがあることを認識しています (遠慮なく訂正してください)。30個ほどのボタンであっても、複数のボタンに適用できる回答が欲しいので、ボタンごとに停止オーディオプレーヤー1、2、および3をコピーして貼り付ける必要はありません。
要約すると、それぞれ 1 つのサウンドを再生する複数のボタンがあります。一度に複数のサウンドを再生したくありません。ボタンをクリックすると、1 つのサウンドが再生され、他のすべてのオーディオ プレーヤーが停止します。簡単にするために、AVAudioPlayer インスタンスを 1 つだけ持つことをお勧めします。前もって感謝します!