how to press key , the object will random to play music and stop music?

how to make a script press keyboard “p” , the object will random to play music and press “i” the object will stop music?

Hi, well first make sure you have defined those keys on Edit—>Project Settings—>Input

Then try this code, it is pretty basic but it will get you started:

var yourSound: AudioSource;

if(Input.GetKeyDown (“p”)){

yourSound.Play();

}

if(Input.GetKeyDown (“i”)){

yourSound.Stop();

}

Greetings

sorry i don’t understand…

but i have a total 3 songs(AMusic, BMusic, CMusic ). i want to press key random play. could you mind teach me how to writer script ?

if i have total 3 musics , Music1 Music2 Music3 , how to random when i press a key p?

#pragma strict
@script RequireComponent(AudioSource)

public var music1 : AudioClip;
public var music2 : AudioClip; 
public var music3 : AudioClip; 
private var randomMusic : int = 0;

function FixedUpdate ()
{
    if(Input.GetKeyDown(KeyCode.P))
	{
		chooseMusic();
		audio.Play();
	}

    if(Input.GetKeyDown(KeyCode.I))
	{
		audio.Stop();
	}
}

function chooseMusic()
{   
    randomMusic = Random.Range(0,3);
    
    switch (randomMusic)
    {
      case 0: 
      	audio.clip = music1; 
      	break;
      case 1: 
      	audio.clip = music2; 
      	break;
      case 2: 
      	audio.clip = music3; 
      	break;
    }
    
    Debug.Log("Current Clip = music"+(randomMusic+1));
}

Make sure the gameObject with this script has an AudioSource component attached to it.
Add this script, then drop your 3 songs in the Inspector.

EDIT :

  • make an empty gameObject
  • add a Component → AudioSource
  • Attach the above script to the gameObject
  • in the gameObject’s Inspector, drag and drop your songs into music1 , 2 , 3
  • hit play