Search code examples
audiounity-game-engineunityscript

Create an audio source and assign a clip in Unity


Folks I'm having trouble creating an audio source and assigning it a clip in Unity.

I'm streaming a file and the debugger tells me it's found the file and it's ready to play using the following code.

@script RequireComponent(AudioSource)

var www : WWW;
var audioSource: AudioSource = gameObject.AddComponent<AudioSource>();
var myAudioClip: AudioClip;


function Start ()
{
      www = new WWW ("file://" + Application.dataPath.Substring (0, Application.dataPath.LastIndexOf ("/")) + "/Assets/intro.wav"); 
      myAudioClip = www.audioClip;
      Debug.Log(myAudioClip.isReadyToPlay);
}

However the debugger gives me errors in my audioSource declaration.

Unexpected Token: )
expecting ), found ';'
'; expected, insert a semicolon at the end.

This error points at the line

var audioSource: AudioSource = gameObject.AddComponent();

Ultimately my aim is to then assign the clip to the audioSource and let rip!


Solution

  • You already have declared that a component of AudioSource is needed;

    @script RequireComponent(AudioSource)
    

    So no need to add it as a component. I don't normally use UnityScript but here's the code you want;

    @script RequireComponent(AudioSource)
    
    var www             : WWW;
    var audioSource : AudioSource;
    var myAudioClip : AudioClip;
    
    function Start () {
        audioSource = GetComponent(AudioSource);
        StartCoroutine( LoadAudio( "file://" + Application.dataPath.Substring (0, Application.dataPath.LastIndexOf ("/")) + "/Assets/intro.wav" ) );
    }
    
    function LoadAudio( path : String ) {
        www = new WWW ( path );
        yield www;
        myAudioClip = www.audioClip;
        Debug.Log(myAudioClip.isReadyToPlay);
    }
    

    To use the WWW class you can use coroutines to wait until it's done loading the asset you require. Or you can keep checking whether www.isDone is true.

    Documentation; http://docs.unity3d.com/ScriptReference/Coroutine.html