- Home /
Dynamic Backgroundmusic
My worldshifting based Game should have 2 background themes. the one of them is a slightly different version of the other one with the same length. What I wanna do is, if I press a specific key, the playing theme should switch to the other one but continue right at that time code where the previous one stopped (for ex.: when 1st. track stops at 0:35, the 2nd track should continue right at that time), whereas in my case its still tarting from the beginning. Any help will be highly appreciated!
My current code:
public class AudioManager : MonoBehaviour {
public AudioSource GTD;
public AudioClip CuteGiana;
public AudioClip DarkGiana;
void Start()
{
GTD = GetComponent<AudioSource>();
GTD.clip = CuteGiana;
GTD.Play();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.P))
{
if (GTD.clip == CuteGiana)
{
GTD.Stop();
GTD.clip = DarkGiana;
GTD.Play();
}
else
{
GTD.Stop();
GTD.clip = CuteGiana;
GTD.Play();
}
}
}
} ,My Game should have 2 background themes, a "light" one and a "dark" one, which has the same length and uses the same melody, but with different samples. Anyway I made the playing theme switch after pressing a key, but I want the other theme to continue right at that time code, where the previous theme stopped (for example: previous theme stopped at 0:35, next theme should continue from there), whereas it's just starting from the beginning at the moment. Any help will be highly appreciated!
Answer by Pinkuboxu · Jul 04, 2019 at 02:15 PM
There are a few ways to do this. Take a look at:
https://docs.unity3d.com/ScriptReference/AudioSource-time.html AND
https://docs.unity3d.com/ScriptReference/AudioSource-timeSamples.html
I think they can be used to set the time, but in case they don't, another method is to use the Audio Mixer and manipulate the Mixer channels volume in code smoothly using what are called Snapshots in the Mixer. This is a bit advanced and requires you to learn how the Mixer works in Unity. In fact you may just want to use this method as it allows you to transition more smoothly rather than just jump right in to another track.
https://docs.unity3d.com/Manual//AudioMixer.html
https://learn.unity.com/tutorial/audio-mixing
https://docs.unity3d.com/ScriptReference/Audio.AudioMixerSnapshot.html
Your answer
Follow this Question
Related Questions
C sharp cant play Audio 2 Answers
Audio Source wont play in if statement 3 Answers
Unity Unable to Reassign Audio Clip 1 Answer
What are the parameters to the AudioClip.create() function 0 Answers