How to play a sound with C#

All the answers I have seen about this are links to the documentation about AudioSource. I can read that documentation but there are now examples of how it’s instantiated in code.

I get that you can add an AudioSource component to a gameObject. But how do you play that in a script attached to the gameObject? Is it something like

AudioSource sound = gameObject.GetComponent<AudioSource>();
sound.Play();

???
But what if you have multiple sounds attached to the game object? I want to randomly play one of these sounds, so how do I find them? I assume it requires a filename (string)?

Also, what if I’d rather specify in code the filenames of the sounds to use? Is it inefficient to call Resources.Load instead of attaching sounds as AudioSource components to gameObjects?

Thanks for your help

I think this can help.

@script RequireComponent(AudioSource)
	public var otherClip: AudioClip;

	// Play default sound
	function Start()
	{
		audio.Play();

		// Wait for the audio to have finished
		yield WaitForSeconds (audio.clip.length);

		// Assign the other clip and play it
		audio.clip = otherClip;
		audio.Play();
	}

so there you have “otherClip” variable which you can fill with audio file because it is AudioClip type.

in C# it would be like “public AudioClip otherClip;”

now with audio.Play() you start playing the default audio.

with “yield…” you tell to the script to wait until sound is over.
then just assign new clip and play it.

btw you can do like a loop with more than 1 sound

	public AudioClip[] otherClip; //make an arrayed variable (so you can attach more than one sound)

	// Play random sound from variable
	void PlaySound()
	{
                //Assign random sound from variable
                audio.clip = otherClip[Random.Range(0,otherClip.length)];

		audio.Play();

		// Wait for the audio to have finished
		yield WaitForSeconds (audio.clip.length);

		//Now you should re-loop this function Like
                PlaySound();
	}

I’m not sure if it would work but if you know SOME of the basics you will be able to fix errors
1st I’m not sure if I assigned array variable correctly
2nd Don’t know if just “PlaySound()” would work for re-looping

3 Likes

Just incase someone else just wants to simply play sound in c#, this works for me:

AudioSource audio = gameObject.addComponent();
audio.PlayOneShot((AudioClip)Resources.Load(“clank1”));

3 Likes

kwokman’s solution worked for me. However, “addComponent” should be “AddComponent”:

AudioSource audio = gameObject.AddComponent();
audio.PlayOneShot((AudioClip)Resources.Load(“clank1”));

Also, the AudioClip appears to only load if “clank1” is within a folder called “Resources”.

If “clank1” isn’t found, Unity won’t issue an error, so to add a notification of a failed attempt to play, my final code looks like this:

AudioSource audio = gameObject.AddComponent();
AudioClip clip = (AudioClip)Resources.Load (“clank1”);
if (clip != null) {
audio.PlayOneShot (clip, 1.0F);
}
else {
Debug.Log ("Attempted to play missing audio clip by name" + audioClipName);
}

2 Likes

I tried it so hard and spend two days to do it. Finally I found the solution. Here, is my c sharp code.

you also can refer this video.

Here is the code, actually very simple code but is working. Hope you can do that too.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class soundExample : MonoBehaviour {

    public AudioClip bcgMusic;
    // Use this for initialization
    void Start () {
        AudioSource.PlayClipAtPoint (bcgMusic, transform.position);
    }
   
    // Update is called once per frame
    void Update () {
       
    }
}
2 Likes

works great thanks!
especially when you use the update function!

Thank You!

In My Situation Anyways lol

You should please create a new thread with your issue. Read this page for how to post code properly (nicely) on the forums: Using code tags properly

If you are using UnityScript (javascript), please consider switching to C#, as Unityscript won’t be supported much longer.

You assume wrong dude. It’s js when the guy asked to show him the example in C#

2 Likes

Please check the dates of the threads you’re replying to. So far 2 out of 2 of your comments have been on threads that are multiple years old. Necroposting is highly frowned upon here, since it dregs up code examples that are obsolete and best left buried (for example: anything having anything to do with Javascript)

Yeah so it doesn’t really matter how much years it’s been, this guy gave the answer to him in js code when he asked him to do it in c#, I don’t really care how much years have passed I just mentioned that to him.

2 Likes