- Home /
Audio Source question
Oh well, my bad if this question was asked before. Actually also my bad for not knowing what to type as the title, but i have a noob question xD
I am working on a simple project to sharpen my skills with mobile, and i have a part on my project that requires the player to press the same button a lot of times continuously. Everytime you press the button, a sound is played. Naturaly, if i press the button again while the sound is still playing, it will stop and restart. But how would i cancel this effect? I wanted the sound to not stop when the button is touched, so if the audio has 5 seconds and you touched the button 10 times in 3 seconds, it would still play the audio 10 times. How could i do this? Can someone explain? Many thanks ^-^
So you want the sound to enqueue multiple times or to play concurrently? For the second you need multiple audio sources, one for each you want to play concurrently.
Thanks, mate! Coding with two audio sources worked as expected =)
Using 2 audio source is not the solution. Note time when you press button and after spending seconds(your desired seconds) again play sound if pressing button. You can use PlayOneShot
if already sound playing.
Not really, i simply used:
if (playedOne == false)
{
sources[0].Play();
playedOne = true;
}
else
if (playedOne == true)
{
sources[1].Play();
playedOne = false;
}
ins$$anonymous$$d of: Audiosource.Play()
use: Audiosource.PlayOneShot(yourSound). It will do what it seems you are trying to do. Caveat: you will have no control over the sound once it is played (like if you wanted to change pitch/volume via script), but it doesn't seem like that is something you need.
Check the docs for how to use volume parameter
https://docs.unity3d.com/ScriptReference/AudioSource.PlayOneShot.html
Answer by · May 29, 2017 at 08:01 PM
You could Instantiate a prefab that contains the audio that you want to play and make it destroy it self when the playback is finished.
This is something I wrote sometime ago. I know that there are better ways of doing this. This script will destroy destroy the gameobject when the sound ends, and it accounts for the pitch value.
public bool autoDestroy;
AudioSource audioSrc;
float startTime;
// Use this for initialization
void Start ()
{
audioSrc = GetComponent<AudioSource> ();
if (autoDestroy) {
startTime = Time.time;
}
}
// Update is called once per frame
void Update ()
{
if(autoDestroy) {
if(((Time.time * Mathf.Abs(audioSrc.pitch)) - (startTime * Mathf.Abs(audioSrc.pitch))) >= audioSrc.clip.length){
Destroy (gameObject);
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612123012im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Make ALL animations stop! 1 Answer
How can i make my 2D character not toppling over 0 Answers
Stopping AudioClip/AudioSource C# 0 Answers
Audio: Does Stop() affect PlayOneShot()? 2 Answers
Problem with many audio sources playing at the same time 1 Answer