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

标签 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];


}

最佳答案

实现此行为取决于您。我建议您跟踪可能正在播放的任何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];
}

关于ios - 如何防止播放多个直播音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23161456/

相关文章:

objective-c - 使用目标文件启动应用程序

audio - 钛金属手机中的高质量音频录制

java - 尝试在我的 ActionListener 中添加播放音频方法

ios - TinyMCE:站点在 iOS 上通过键盘输入跳回到顶部

ios - 为什么不调用连接 didFailWithError ?

objective-c - 在 iOS 中保持套接字连接

audio - FFMPEG 改变音调频率(音高音频)

ios - 无效的包 - Info.plist 应该使用包含单个平台的数组指定 CFBundleSupportedPlatforms

ios - Swift - 不能从 subview Controller 调用公共(public)函数? ViewController has no member错误?

ios - 插入多个字符时关闭文本字段