Hi there.
I’d like to play wav file from Web URL.
I attached AudioSource componento to my GameObject .
And I created the method.
private void PlaySoundFromURL (string url)
{
// url = System.Uri.EscapeUriString (url);
Debug.Log (url);
WWW www = new WWW(url);
audio.clip = www.audioClip;
audio.Play();
}
And, I tried it
PlaySoundFromURL ("http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/Samples/AFsp/M1F1-Alaw-AFsp.wav");
But, the sound file didn’t play.
Could you tell me how to play the file?
Hi
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class Getaudio : MonoBehaviour {
public string url;
private AudioSource audio;
// Use this for initialization
IEnumerator Start () {
audio = GetComponent<AudioSource>();
while(true){
if(Input.GetKeyDown(KeyCode.Space)){
yield return StartCoroutine("PlaySoundFromURL",url);
}
yield return null;
}
}
// Update is called once per frame
void Update () {
}
private IEnumerator PlaySoundFromURL(string url)
{
// url = System.Uri.EscapeUriString (url);
Debug.Log (url);
WWW www = new WWW(url);
yield return www;
audio.clip = www.audioClip;
audio.Play();
}
}
You can’t play an audio file from the web instantly! You’ll have to wait till it gets downloaded and then play it. To do this, you can use a coroutine:
IEnumerator PlaySoundFromURL (string url)
{
WWW www = new WWW(url);
while (!www.isDone)
yield return null;
audio.clip = www.audioClip;
audio.Play();
}
To play it:
StartCoroutine (PlaySoundFromURL ("http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/Samples/AFsp/M1F1-Alaw-AFsp.wav"));
You should wait for the file to be downloaded:
bool Play = false;
private IEnumerator PlaySoundFromURL (string url) {
// url = System.Uri.EscapeUriString (url);
Debug.Log (url);
WWW www = new WWW(url);
yield return www;
Debug.Log("The file has been downloaded, playing it");
audio.clip = www.audioClip;
play = true;
Debug.Log("Audio played");
}
AudioSource audio;
void Update() {
if (play) {
if (!source.isPlaying && source.clip.isReadyToPlay) {
audio.play();
}
}
}
public void PlayTheSound(string URL) {
StartCoroutine(PlaySoundFromURL(URL);
}
string url = "http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/Samples/AFsp/M1F1-Alaw-AFsp.wav";
void Start() {
audio = GetComponent<AudioSource>();
PlayTheSound(url);
}