如何防止播放多个直播音频?

时间:2014-04-18 20:05:36

标签: ios objective-c audio avaudioplayer

我目前正在制作直播音乐应用,并且我已经完成了所有按钮的工作和播放声音。

然而,如果正在播放一个声音,当我按下另一个按钮,而不是停止原始声音时,它只是播放它,请帮我解决这个问题?

非常感谢

- (IBAction)Play1:(id)sender {

    NSString *stream = @".mp3"
    ;

    NSURL *url = [NSURL URLWithString:stream];

    NSURLRequest *urlrequest = [NSURLRequest requestWithURL: url];

    [Webview1 loadRequest:urlrequest];
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

    [[AVAudioSession sharedInstance] setActive: YES error: nil];

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    [audioPlayer play];

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];


}

1 个答案:

答案 0 :(得分:1)

由您来实现此行为。我建议你跟踪任何可能正在播放的AVAudioPlayer,并在创建和开始新的AVAudioPlayer之前将其停止。

例如,您可以使用属性来存储您创建的每个AVAudioPlayer。然后,在创建新的之前,停止旧的。

有很多方法可以做到这一点。假设您有每个按钮的URL,这是一个可能的过程:

// note that audioPlayer is a property. It might be defined like this:
// @property (nonatomic,strong) AVAudioPlayer *audioPlayer

- (IBAction)button1Pressed:(id)sender {
    NSString *stream = @"url1.mp3";
    [self playUrl:[NSURL URLWithString:stream]];
}

- (IBAction)button2Pressed:(id)sender {
    NSString *stream = @"url2.mp3";
    [self playUrl:[NSURL URLWithString:stream]];
}

- (void) playUrl:(NSURL *) url {
    //stop a previously running audioPlayer if it is running:
    [audioPlayer pause]; //this will do nothing if audioPlayer is nil
    //create a new one and start it:
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [audioPlayer start];
}