您可以使用类似这样的相同代码创建多个 AudioPlayer 实例
在 .h 文件中
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface MultipleChoiceViewController : UIViewController<AVAudioPlayerDelegate>
{
AVAudioPlayer *dingAudioPlayer;
AVAudioPlayer *buzzAudioPlayer;
}
-(IBAction) playDingAudio:(id) sender;
-(IBAction) playBuzzAudio:(id) sender;
在你的 .m 文件中
- (void)viewDidLoad
{
dingAudioPlayer = [self loadAudio:@"ding Audio" audioType:@"mp3"];
buzzAudioPlayer = [self loadAudio:@"buzz Audio" audioType:@"mp3"];
[buzzAudioPlayer play];
}
- (AVAudioPlayer *)loadAudio:(NSString *)filename audioType:(NSString *)audioType{
NSURL * url = [[NSBundle mainBundle] URLForResource:filename withExtension:audioType];
NSError * error;
AVAudioPlayer * player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (!player) {
NSLog(@"Error loading %@: %@", url, error.localizedDescription);
} else {
player.delegate = self;
[player prepareToPlay];
}
return player;
}
#pragma mark - AvAudio Player delegate methods
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
if (player != dingAudioPlayer && player != buzzAudioPlayer) {
player = nil;
}
NSLog(@"finished");
}
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
NSLog(@"AVAudioPlayer Error : %@",error);
}
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
}
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player
{
}
-(IBAction) playDingAudio:(id) sender{
[dingAudioPlayer play];
}
-(IBAction) playBuzzAudio:(id) sender{
[buzzAudioPlayer play];
}