1

在我的应用程序中,我显示 5UIView并且通过触摸任何视图声音都会播放。那么如何AVAudioPlayer在同一个 ViewController 中添加多个。

对于单个视图,我正在添加此代码以实现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实例并添加到每个视图中,还是以任何其他方式为每个视图重用此代码?

4

3 回答 3

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];
}
于 2013-08-02T04:31:06.720 回答
0

你可以用一个来实现它AVAudioPlayer,你必须为你所有的5个视图创建一个通用方法,当你的触摸方法根据视图调用时,你可以设置声音文件AVAudioPlayer

于 2013-07-30T07:54:57.967 回答
0

仅使用一个 AVAudioPlayer 实例来播放声音。您所要做的就是,为每个视图分配不同的声音,并为所有视图分配相同的播放声音方法。

制作 5 个类似的网址

NSURL *urlsound1 = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"MP3"]];
NSURL *urlsound2 = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"MP3"]];

将 urls 作为参数传递给 play 方法

于 2013-07-30T08:14:14.163 回答