- Home /
This post has been wikified, any user with enough reputation can edit it.
Car horn sound looping problem C#
Hey guys, I am trying to make a car horn script written in C#. I have a sound that I looped in audacity and I am using it in the script. The problem is that when I try to make it loop in Unity the sound is full of clicks and is inconsistent when I change the FPS. Other sound looping scripts posted on the forum had similar issues. Any idea what is causing the clicks?
Here's the script:
using UnityEngine; using System.Collections;
public class Horn : MonoBehaviour {
public AudioSource horn; //The horn audioSource
public AudioClip[] hornSounds = new AudioClip[1]; //All the game's horn sounds
public int hornType = 0; //What horn sound the car will be assigned
public bool honking = false; //Is the car using the horn?
public float volume = 1.0f; //The audioSource volume
public float volumeMin = 0f; //Sets a minimum volume
public float pitch = 0.976f; //The audioSource pitch
public float coolDownMax; //Maximum value for the coolDown
public float coolDown; //The delay inbetween horn sounds
public float startTime; //Loop start time
public float waitTime; //Loop end time (restart)
public float hornDisturbance = 2f; //AI reaction to horn sounds (Ignore)
public float hornFadeSpeed = 7.0f; //How fast the horn sound fades
void Start () {
var audio = horn.GetComponent<AudioSource>();
if (hornType == 0 || hornType > hornSounds.Length)
Debug.LogWarning("Horn sound not found");
else
audio.clip = hornSounds[hornType-1];
audio.volume = volume;
audio.pitch = pitch;
}
void Update () {
var audio = horn.GetComponent<AudioSource>();
if (Input.GetButtonDown("Horn") && horn != null && honking == false) {
audio.time = 0;
audio.volume = volume/2;
coolDown = 0;
honking = true;
}
if (Input.GetButton("Horn") && horn != null && honking == true) {
audio.volume = Mathf.Lerp(audio.volume, volume, 30 * Time.deltaTime);
if(audio.time > waitTime * audio.clip.length)
audio.time = startTime * audio.clip.length;
if(!audio.isPlaying) {
coolDown -= 1 * Time.deltaTime;
honking = true;
if (coolDown <= 0) {
audio.PlayOneShot(horn.GetComponent<AudioSource>().clip);
coolDown = coolDownMax;
}
}
} else {
honking = false;
coolDown = coolDownMax;
audio.volume = Mathf.Lerp(audio.volume, 0, hornFadeSpeed * Time.deltaTime);
audio.volume = Mathf.Clamp(audio.volume, volumeMin, volume);
if (audio.volume <= volumeMin) {
audio.Stop();
}
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613201457im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Car engine sound 1 Answer
Character Rides In Vehicle 1 Answer
AudioClip[] bug 1 Answer
Stop audio looping on Input.GetButtonUp 0 Answers
How to make AudioSource play defined clips using String? 1 Answer