使用AVAudioPlayer一次播放多种声音 [英] Playing Multiple Sounds at Once Using AVAudioPlayer

查看:78
本文介绍了使用AVAudioPlayer一次播放多种声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组UIButton.每当我按下一个按钮时,都会播放声音.问题是:当您按下一个按钮并播放后面的声音时,当您按下第二个按钮时,来自第一个按钮的声音就会停止.

I have a set of UIButtons. Every time I press a button, a sound plays. The issue: When you press one button and the sound behind to play, when you press the second button the sound coming from the first button stops.

这个问题被问了一百万遍.解决方案始终是每次都创建一个新的AVAudioPlayer实例.我已经尝试过了,但无济于事.我已经阅读了文档,通读了与此相关的StackOverflow上的每个问题,但没有运气.当我使用SystemSoundID时,它们每次都同时播放...但是我必须牺牲音量控制能力.这是我正在使用的代码:

This question has been asked a million times. The solution is always to create a new instance of AVAudioPlayer each time. I've tried that, to no avail. I've read the docs, read through every question on StackOverflow related to this, and have had no luck. When I use SystemSoundID they play simultaneously each time... But I have to sacrifice volume control ability. Here is the code I'm working with:

 NSString *soundOne = [[NSUserDefaults standardUserDefaults] valueForKey:senderString];

    NSURL *url = [NSURL URLWithString:[soundOne stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

    switch ([sender tag]) {

        case 1:
            [_audioPlayer prepareToPlay];
            [_audioPlayer play];
            NSLog(@"Playing: %@", soundOne);
            break;

        case 2:
            [_audioPlayer prepareToPlay];
            [_audioPlayer play];
            NSLog(@"Playing: %@", soundOne);
            break;
}

推荐答案

问题是您的代码在制作新的音频播放器的同时也会破坏旧的音频播放器.您必须同时有两个音频播放器 才能使它们同时播放两种声音.如果只有一个实例变量_audioPlayer,则不可能发生这种情况.

The problem is that your code, while making a new audio player, also destroys the old audio player. You have to have two audio players existing at the same time in order to get them to play two sounds at the same time. That can't possibly happen when you have only one instance variable _audioPlayer.

这篇关于使用AVAudioPlayer一次播放多种声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆