我将屏幕的三个区域定义为“热点”,因此如果检测到任何触摸,它会播放特定区域的声音。一切都很好,除了如果我点击区域 1,然后点击区域 2,区域 2 的声音会切断区域 1。我希望任何区域的声音播放直到完成。因此,如果我点击区域 1,然后点击区域 2,区域 1 的声音将继续播放,区域 2 将在区域 1 之上播放。
这是我目前拥有的代码(工作正常,但不允许音频重叠):
if(point.y < 316 && point.y > 76 && point.x < 220 && point.x > 200)
{
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/sound1.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];
}
if(point.y < 316 && point.y > 76 && point.x < 260 && point.x > 240)
{
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/sound2.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];
}
if(point.y < 316 && point.y > 76 && point.x < 300 && point.x > 280)
{
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/sound3.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];
}
谁能帮我弄清楚如何让这些声音重叠?谢谢!
最佳答案
看起来您只是为每种情况重新分配 audioPlayer。如果 audioPlayer 已经在播放一种声音,然后您重新分配它播放另一种声音,则原始 audioPlayer 将被销毁并停止播放。
我过去解决这个问题的方法是设置多个 AVPlayer 对象,比如:
AVPlayer *_player[MAX_CHANNELS];
NSUInteger _currentChannel;
接着玩:
_player[_currentChannel] = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
_currentChannel++;
if (_currentChannel == MAX_CHANNELS) {
_currentChannel = 0;
}
那么您不会获得无限数量的重叠音效,但您可以将一些“合理”数量预定义为 MAX_CHANNELS,并在下一个声音停止第一个声音之前拥有那么多重叠效果。
关于ios - 如何让多个音频流在 iOS 中重叠播放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16681668/