audio.play does not work
I have used WWW.GetAudioClip() to import a song at runtime into my game. The import works perfectly, but when I try and play my sound, it does not play.
public AudioSource adio;
public void Start()
{
WWW www = new WWW("file://C:/sound.ogg");
AudioClip a = www.GetAudioClip(true, false, AudioType.OGGVORBIS);
adio.clip = a;
adio.Play();
Debug.Log (adio.isPlaying);
}
The debug says that the sound is in fact not playing, but in the AudioSource component, I can clearly see that there is a clip variable, and I can even manually listen to it if I click on it and listen through the editor, so it's not a problem with the import.
What could possibly be causing the audio to not play? I have also tried adding a delay and using PlayOneShot(). playOnAwake makes no difference regardless of it's setting either.
i have a similar prob as you but in my case PlayOneShot is the only way to get it playing but its terrible thats way. i've got this prob since i did upgrade to 5.3.2 never had this prob before. all sounds working well but this new one since 5.3 maybe its a bug ???
Sorry, but I never did figure out what the problem was or how to fix it.
Answer by TBruce · Jul 17, 2016 at 08:15 PM
The problem with trying to play an audio clip with www is that if you do not wait until the audio has not completely loaded before trying to play the clip it will not properly work. Try this class out
using UnityEngine;
using System;
using System.IO;
using System.Collections;
public class PlayAudioFile : MonoBehaviour
{
public AudioSource adio;
public string filePath = "file://C:/sound.ogg";
private AudioClip audioClip;
public void Start()
{
StartCoroutine(LoadAndPlaySound(filePath));
}
IEnumerator LoadAndPlaySound(string filePath)
{
WWW www = new WWW(filePath);
while(!www.isDone)
yield return null;
if ((www.bytesDownloaded > 0) && (www.audioClip != null))
{
// audioClip = www.GetAudioClip(false);
audioClip = www.GetAudioClip(true, false, AudioType.OGGVORBIS);
while (!audioClip.isReadyToPlay)
yield return www;
audioClip.name = Path.GetFileNameWithoutExtension(filePath);
PlayAudioClip();
}
yield return null;
}
public void PlayAudioClip()
{
if ((audioClip != null) && (audioClip.isReadyToPlay))
{
adio.PlayOneShot(audioClip);
}
}
}
Your answer
Follow this Question
Related Questions
Play audio once not working 0 Answers
Audio is cut in script 0 Answers
Need help: new sound isnt played correctly anymore 2 Answers