如何在同一个ViewController中添加多个AVAudioPlayer

时间:2013-07-30 07:47:34

标签: iphone ios avaudioplayer

在我的应用程序中,我显示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瞬时并添加到每个视图或任何其他方式来为每个视图重用此代码吗?

3 个答案:

答案 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"]];

将网址作为参数传递给播放方法