Loading and playing an audio file from disk with C#?

Hi everyone, I’m attempting to create a script that lets the player press a key to open a file chooser, to select a song to play. This is my script right now:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class audioInputControl : MonoBehaviour {
    List<string> songs = new List<string>();
    public AudioSource source;
    public WWW www;
    // Use this for initialization
    void Start () {
        source = GetComponent<AudioSource>();
    }
  
    // Update is called once per frame
    void Update () {
        if(Input.GetKeyDown(KeyCode.L))
        {
        songs.Add(UnityEditor.EditorUtility.OpenFilePanel("Add Song...", "C:/", "wav"));
        if(source.clip == null)
        {
            www = new WWW(songs[0]);
            source.clip = www.audioClip;
            source.Play();
        }
        }
        if(!source.isPlaying && source.clip != null)
        {
            www = new WWW(songs[0]);
            songs.Remove(songs[0]);
            Debug.Log("playing audio file " + songs[0]);
            source.clip = www.audioClip;
            source.Play();
        }
    }
}

Everything seems to be working fine (to my untrained eye) but no audio is playing. Also, for some reason the code inside the if statement that checks if the audio is playing executes even after source.Play() has run. Other audio in the scene is working fine. Any help would be really appreciated!

NOTE: I posted this thread in the Audio section as well, but didn’t get any responses. Thought I’d put it here too.

1st: you need to supply something like “file://C:/dir/file.wav” to WWW. It needs file:// part.
2nd: AudioSource isn’t loaded instantly. You need to wait until its state is Loaded. I’d do something like Coroutine:

public IEnumerator StartSong(string path)
{
    www = new WWW(path);
    if (www.error != null)
    {
        Debug.Log(www.error);
    }
    else
    {
        source.clip = www.audioClip;
        while (source.clip.loadState != AudioDataLoadState.Loaded)
            yield return new WaitForSeconds(0.1f);
        source.Play();
    }
}

3rd: your code won’t work in compiled version as it relies on UnityEditor.EditorUtility.OpenFilePanel(…).

Thanks for the reply! Really useful tips! That’s a shame about the file panel, is there any built-in file picker that works after the program is compiled?

[quote=“gristly, post:3, topic: 614559, username:gristly”]
is there any built-in file picker that works after the program is compiled
[/quote]Built-in - no, there isn’t any. There are supposedly free ones on asset store though: https://www.assetstore.unity3d.com/en/#!/content/18308 or you can always write your own.