1

EDIT! I got it working by moving the source.play up into a function in update and now I'm calling it with a boolean.

I'm at the moment coding a VR drum set in Unity and I need Unity to play a sound when it recieves an OSC message from the input device. All the OSC I've got working, but when I want to play the sounds it just stops completely.

I have 2 audioclips that I want to change between and I've tried with 2 audiosources and 1 audiosource with several audioclips but both without luck. I have a debug running and it runs the start of the command but then stops before getting to the debug.log print.

 if ((int)oscVal == 3)
        {
            lastTime2 = currentTime;
            DC.isActive2 = true; //It runs to this part here and then stops 
            source2.Play(); //This line doesn't seem to run
            Debug.Log("Activated Drum2"); //This line doesn't run either
        }

I want the command to run and play the sound and keep on running. It doesn't do it and just stops midways through the command.

Andreas2200
  • 47
  • 3
  • 6
  • if it stops before going to the next line, the error must be in the previous lines. Have you tried playgin the sounds basd on another trigger, like keyboard? – zambari Apr 25 '19 at 09:46
  • I've tried to bind it to a key press, but it doesn't trigger. I also tried letting it play on awake and that works fine, but I still can't get it to play. – Andreas2200 Apr 25 '19 at 10:46
  • Edit* it works with the key press – Andreas2200 Apr 25 '19 at 11:08

1 Answers1

1

First You need to Define AudioSource Variable and assign the Audio Clip to it threw the Editor and you can use this code for this

public AudioSource audioSource;
public AudioClip clip;

public void PlayMusic( bool isLoopSound) 
  { 
       audioSource.clip =clip;
       if (isLoopSound) {
            audioSource.loop = true;
        }
        else {
            audioSource.loop = false;
        } 
   }

Second if you want to play music from a file path

 public AudioSource audioSource;

 public IEnumerator PlayMusicFromPath(string filePath, bool isLoopSound)
    {
        if (File.Exists(filePath)) {
            using (WWW www = new WWW("file://" + filePath)) {   
                yield return www;
                if(www != null) {
                    audioSource.clip = www.GetAudioClip();
                    if (isLoopSound) {
                        audioSource.loop = true;
                    }
                    else {
                        audioSource.loop = false;
                    }
                    audioSource.Play();
                    yield return null;
                }
                else {
                    Debug.Log("WWWW is null");
                    yield return null;
                }
            }
        }
        else
        {
            yield return null;
        }
    }
Qusai Azzam
  • 465
  • 4
  • 19