播放时多个音频文件重叠



我在播放声音文件时遇到问题:我有多个按钮,每个按钮都与一个声音文件关联。例如,当播放声音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

这段代码完成了任务。。。此外,作为奖励,您的应用程序只需加载一次音乐文件!

// 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

最新更新