在我的应用程序中,我显示5 UIView
并触摸任何视图声音将播放。那么如何在同一个ViewController中添加多个AVAudioPlayer
。
对于单一视图,我添加此代码以实现AVAudioPlayer
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"MP3"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (error)
{
NSLog(@"Error in audioPlayer: %@", [error localizedDescription]);
} else {
audioPlayer.delegate = self;
//theAudio.numberOfLoops = -1;
[audioPlayer prepareToPlay];
}
那么我应该创建5个AVAudioPlayer
瞬时并添加到每个视图或任何其他方式来为每个视图重用此代码吗?
答案 0 :(得分:2)
您可以使用与此相同的代码创建多个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];
}
答案 1 :(得分:0)
您可以使用一个AVAudioPlayer
来实现它,您必须为所有5个视图创建一个常用方法,当您根据视图调用触摸方法时,您可以设置AVAudioPlayer
的声音文件。
答案 2 :(得分:0)
仅使用一个AVAudioPlayer实例播放声音。您所要做的就是,为每个视图分配不同的声音,并为所有视图指定相同的播放声音方法。
制作5个网址,如
NSURL *urlsound1 = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"MP3"]];
NSURL *urlsound2 = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"MP3"]];
将网址作为参数传递给播放方法