简体   繁体   English

使用AVAudioPlayer彼此播放声音

[英]Sounds playing over each other using AVAudioPlayer

Right, sorry if i seem like a noob, but i'm new to xcode. 是的,对不起,如果我看起来像个菜鸟,但是我是xcode的新手。 I'm currently making a soundboard, and i've got all the buttons to work and play sounds from them. 我目前正在制作音板,并且所有按钮都可以工作并从中播放声音。

However, if one sound is playing, when i press another button, rather than stopping the original sound, it just plays over it, so i was wandering if anyone knew how to fix this? 但是,如果正在播放一种声音,则当我按下另一个按钮时,它只是播放原始声音,而不是停止播放原始声音,所以我在徘徊,如果有人知道如何解决此问题?

Here's the code i'm using for the buttons: 这是我用于按钮的代码:

- (IBAction)playsound {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Gold" ofType:@"mp3"];
    AVAudioPlayer* myAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    myAudio.delegate = self;
    myAudio.volume = 2.0;
    myAudio.numberOfLoops = 0;
    [myAudio play];
}

I'd be really grateful if someone could help me out. 如果有人可以帮助我,我将不胜感激。

Thanks. 谢谢。

If the other sound is still playing, you need to tell it to stop. 如果其他声音仍在播放,则需要告诉它停止播放。 You probably want to look into using the calling the stop method on the other AVAudioPlayer. 您可能想研究在另一个AVAudioPlayer上使用stop方法。 So, something like where you have: 因此,类似您所拥有的位置:

[myAudio play];

...insert a method call just before that to tell the other sound to stop. ...在此之前插入一个方法调用,以告知其他声音停止播放。

[myOtherAudioThatsPlaying stop];
[myAudio play];

It might make sense to also browse the AVAudioPlayer documentation . 也可以浏览AVAudioPlayer文档

While bobtiki's answer is formally correct, it only makes sense to call the stop method if you want to do something useful with the sound after it has stopped, for example start playing it again. 尽管bobtiki的回答在形式上是正确的,但只有在您想要在声音停止后对声音做一些有用的事情(例如重新开始播放)时,才调用stop方法才有意义。 Since you just want to get rid of it, I recommend have the player just get deallocated, which automatically makes the sound stop playing. 由于您只是想摆脱它,所以我建议将播放器放掉,这将自动使声音停止播放。 So, instead of 所以,代替

 AVAudioPlayer* myAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 

add an instance variable to your class: 将一个实例变量添加到您的类中:

AVAudioPlayer* myAudio;

then just use 然后就用

  myAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 

Everytime a new sound is played, myAudio gets assigned a new pointer and the old AVAudioPlayer just gets deallocated. 每次播放新声音时,都会为myAudio分配一个新的指针,而旧的AVAudioPlayer会被释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM