0

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

#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
4

1 回答 1

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
于 2013-07-08T00:43:46.257 回答