using WWW to play audio

Hi,
Recently, I’ve been trying to load the music file(.mp3 or .ogg) selected by user to play. With an android plugin, I can get the file path. Here comes my question, how can I use www with file path to locate audio file and attach it to a audio source to play? My code is described below.

public string url = “file://”;
public AudioSource song;
// filepath is something like /mnt/sdcard/123.mp3
void MyFunction()
{
url = url + filepath;
WWW www = new WWW(url);
song.clip = www.audioClip;
song.Play();
}

If someone has the answer, please give me some help with this. Thanks.

Try this:

It allows you to stream music from disc. See also the WWW.GetAudioClip unity reference.

        void Update()
        {
            if (!audioSrc.audio.isPlaying && audioSrc.clip.isReadyToPlay)
            {
                WWW www = new WWW(url);  // start a download of the given URL
                audioSrc.audio.clip = www.GetAudioClip(false, true); // 2D, streaming
                audioSrc.audio.Play();
            } else
            {
                Debug.Log("waiting...");
            }
        }

Use an attribuut AudioSource audioSrc, this would be your AudioSource object or component.

1 Like

Wow, that works. You are awesome!! Thanks for helping me out.

1 Like

There is one more thing, is there any solution for me to jump to the certain point of music to play. For example, with a input time I would make audio play at the input time. I tried audio.PlayScheduled()… but it seems not helpful.

As described in the Unity3D AudioSource Reference, function PlaySheduled does this:

My guess is that you don’t use AudioSettings.dspTime, but just want to do some playback. So, what you do need, is the variable time of the AudioSource component, see AudioSource.time here. And just set it like this:

audioSrc.time = 10 // 10 seconds (allows double, no float)

in which audioSrc is your AudioSource component.

1 Like

Thanks for replying. I did made it work. I set “audio.time” to my specific time and that worked just fine!!!

1 Like