Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to play a sound with C#

Discussion in 'Scripting' started by so_troll, Oct 20, 2013.

  1. so_troll

    so_troll

    Joined:
    Oct 19, 2013
    Posts:
    5
    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

    Code (csharp):
    1. AudioSource sound = gameObject.GetComponent<AudioSource>();
    2. 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
     
  2. HrC123

    HrC123

    Joined:
    Feb 2, 2011
    Posts:
    140
    http://docs.unity3d.com/Documentation/ScriptReference/AudioSource-clip.html

    I think this can help.

    Code (csharp):
    1. @script RequireComponent(AudioSource)
    2.     public var otherClip: AudioClip;
    3.  
    4.     // Play default sound
    5.     function Start()
    6.     {
    7.         audio.Play();
    8.  
    9.         // Wait for the audio to have finished
    10.         yield WaitForSeconds (audio.clip.length);
    11.  
    12.         // Assign the other clip and play it
    13.         audio.clip = otherClip;
    14.         audio.Play();
    15.     }
    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



    Code (csharp):
    1.  
    2.     public AudioClip[] otherClip; //make an arrayed variable (so you can attach more than one sound)
    3.  
    4.     // Play random sound from variable
    5.     void PlaySound()
    6.     {
    7.                 //Assign random sound from variable
    8.                 audio.clip = otherClip[Random.Range(0,otherClip.length)];
    9.  
    10.         audio.Play();
    11.  
    12.         // Wait for the audio to have finished
    13.         yield WaitForSeconds (audio.clip.length);
    14.  
    15.         //Now you should re-loop this function Like
    16.                 PlaySound();
    17.     }
    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. kwokman

    kwokman

    Joined:
    Jan 14, 2015
    Posts:
    1
    Just incase someone else just wants to simply play sound in c#, this works for me:

    AudioSource audio = gameObject.addComponent<AudioSource >();
    audio.PlayOneShot((AudioClip)Resources.Load("clank1"));
     
    Bl4ckh34d and Wachalala like this.
  4. wbknox

    wbknox

    Joined:
    Aug 1, 2016
    Posts:
    11
    kwokman's solution worked for me. However, "addComponent" should be "AddComponent":

    AudioSource audio = gameObject.AddComponent<AudioSource >();
    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<AudioSource >();
    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);
    }
     
    Last edited: Aug 4, 2016
    Analyzer2000 likes this.
  5. mafanbong8819

    mafanbong8819

    Joined:
    Feb 2, 2017
    Posts:
    8
    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.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class soundExample : MonoBehaviour {
    7.  
    8.     public AudioClip bcgMusic;
    9.     // Use this for initialization
    10.     void Start () {
    11.         AudioSource.PlayClipAtPoint (bcgMusic, transform.position);
    12.     }
    13.    
    14.     // Update is called once per frame
    15.     void Update () {
    16.        
    17.     }
    18. }
    19.  
     
    korial1970 likes this.
  6. metaldc4life

    metaldc4life

    Joined:
    Sep 26, 2014
    Posts:
    179
    works great thanks!
    especially when you use the update function!


    Thank You!

    In My Situation Anyways lol
     
  7. darcyj

    darcyj

    Joined:
    Feb 1, 2018
    Posts:
    1
  8. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
  9. Prisec

    Prisec

    Joined:
    Mar 12, 2020
    Posts:
    3
    You assume wrong dude. It's js when the guy asked to show him the example in C#
     
    antropovp and elxde like this.
  10. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,773
    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)
     
  11. Prisec

    Prisec

    Joined:
    Mar 12, 2020
    Posts:
    3
    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.
     
    antropovp and elxde like this.