Reputation: 47
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.
Upvotes: 1
Views: 1081
Reputation: 530
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;
}
}
Upvotes: 1