播放时多个音频文件重叠

时间:2013-07-07 23:26:55

标签: ios avaudioplayer

播放声音文件时遇到问题:我有多个按钮,每个按钮都与一个声音文件相关联。例如,当声音n.1正在进行时,我按下按钮开始声音n.2,这两个声音重叠。我希望每个按钮在按下时停止另一个按钮播放的音频。这是我的.h文件和我的.m文件的一部分。我尝试过“if”,但是我收到了“使用未声明的标识符”错误。请记住,我是一个绝对的初学者,提前谢谢你。

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController <AVAudioPlayerDelegate> {}

-(IBAction)playSound1;
-(IBAction)playSound2;

@end

@implementation ViewController

-(IBAction)playSound1{
    NSString *path=[[NSBundle mainBundle] pathForResource:@"12-Toxicity" ofType:@"mp3"];
    AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]error:NULL];
    theAudio.delegate=self;
    [theAudio play];

}

@end

1 个答案:

答案 0 :(得分:0)

此代码完成了这项工作......而且,作为奖励,您的应用只需加载音乐文件一次!

// ViewController.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController <AVAudioPlayerDelegate>

@property (strong) AVAudioPlayer* sound1Player;
@property (strong) AVAudioPlayer* sound2Player;
- (IBAction)playSound1;
- (IBAction)playSound2;

@end

// ViewController.m

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    NSString *pathOne = [[NSBundle mainBundle] pathForResource:@"12-Toxicity" ofType:@"mp3"];
    if (pathOne) {
        self.sound1Player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathOne] error:NULL];
        self.sound1Player.delegate = self;
    }

    NSString *pathTwo = [[NSBundle mainBundle] pathForResource:@"13-Psycho" ofType:@"mp3"];
    if (pathOne) {
        self.sound2Player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathTwo] error:NULL];
        self.sound2Player.delegate = self;
    }
}

- (IBAction)playSound1 {
    if (self.sound2Player.playing)
        [self.sound2Player stop];
    [self.sound1Player play];
}

- (IBAction)playSound2 {
    if (self.sound1Player.playing)
        [self.sound1Player stop];
    [self.sound2Player play];
}

@end