如何使用AVAudioPlayer发布声音?

时间:2011-03-08 21:16:42

标签: cocoa-touch cocoa avaudioplayer

我正在尝试使用AVFoundation框架创建一个带有很多按钮的音板的“交互式采访”。音板已经完成,但是我有一个问题,当我按下我的一个声音时,当我同时按下一个新声音时它不会停止。如果按下新声音,是否有一种简单的方法可以停止先前的声音?我的代码看起来像这样

- (IBAction)playSound0 {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"about" ofType:@"mp3"];
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

    [theAudio play];
}

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

    [theAudio play];
}

- (IBAction)playSound2 {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"gethighorgetlow" ofType:@"mp3"];
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

    [theAudio play];
}

- (IBAction)playSound3 {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"icamefromthere" ofType:@"mp3"];
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

    [theAudio play];
}

- (IBAction)playSound4 {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"idoeverythinggood" ofType:@"mp3"];
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];


    [theAudio play];

}

1 个答案:

答案 0 :(得分:0)

我会让我的班级跟踪上次开始的声音,在我开始播放新声音之前,停止前一个声音,如果还在播放的话。

AVAudioPlayer有 stop 方法来停止声音,还有一个播放方法来查看它是否正在播放。