Playing looped sound while holding button is distorted
I'm trying to get a looped sound effect to play while holding down a button to charge a projectile like Metroid/Mega Man. I have two different types of projectiles that can be charged, so two different looped clips. Both clips loop fine and sound great when I play them looped in the inspector but when they play in game, they're both very loud and distorted. Here's the script:
private AudioSource sound;
public AudioClip blueCharge;
public AudioClip redCharge;
void Awake()
{
sound = GetComponent<AudioSource>();
}
void Update()
{
if (blueCharging)
{
sound.PlayOneShot(blueCharge);
}
else
if (redCharging)
{
sound.PlayOneShot(redCharge);
}
}
The two bools are just bools from another script that tell me what weapon is selected and the button is being held down. The Audio Source is hooked up to a Audio Mixer Output, which I haven't messed with at all, and no matter if I set Loop to true or false in the inspector, it makes no difference. What could I be doing wrong?
$$anonymous$$ost likely playing audio clip goes into loop. In this case, quick fix can be checking if sound/AudioSource is playing any clip. If not, play sound.
if (blueCharging && !sound.IsPlaying)
Answer by MCoburn · Nov 24, 2015 at 01:00 AM
You're possibly experiencing audio overlap, which is two sounds at the same position in space playing at the same time. Since the audio both overlap, the volume becomes louder, and can lead to distortion.
Adding what Avietry suggested will make it only play should the sound not be playing. If it's playing, then it'll do nothing and carry on. Else, it'll play the sound.
That was it, though I had to do it like
if(blueCharging)
{
if(!sound.isPlaying)
blah blah blah
}
For it to work. Thank you both very much!
Answer by Mich_9 · Nov 24, 2015 at 03:23 PM
That's because you are creating instances of the same sound effect again and again every frame update, for that is PlayOneShot.
private AudioSource sound;
public AudioClip blueCharge;
public AudioClip redCharge;
void Awake()
{
sound = GetComponent<AudioSource>();
}
void Update()
{
bool ischarging = false;
//Set audioclip to play
if (blueCharging)
{
sound.clip = blueCharge;
ischarging = true;
} else if (redCharging)
{
sound.clip = redCharge;
ischarging = true;
} else
{//Optional
sound.Stop();//Stop playing the audio if not charging
}
//Check if the sound is not already playing and if is charging
if (!sound.isPlaying && ischarging)
{
sound.Play();
}
}
Your answer
Follow this Question
Related Questions
Need help: new sound isnt played correctly anymore 2 Answers
Second AudioClip won't play 0 Answers
Audio is way too soft on mobile but alright in Unity Editor! 0 Answers
Play sound within limited region 2 Answers
Audio cut off in new WebGL builds 0 Answers