Load ogg file into audioclip

Hi,
I created a little audio editor i need as tool for a game, were other people are able to edit custom audio files. So I can’t load them through resources.load.
I at least came up wir using the www class. but the problem is, that I need to use Coroutines to make it work - i can’t get around it.
Here is my code so far:

	public static AudioClip GetAudioClip(string mp3FileName) {
		string s = MP3_FILENAME_UMLAUT_CODE_CHAR.ToString();
		mp3FileName = mp3FileName.Replace("ö", "o" + s).Replace("Ö", "O" + s).Replace("ü", "u" + s).Replace("Ü", "U" + s).Replace("ä", "a" + s).Replace("Ä", "A" + s).Replace("ß", "s" + s).Replace(" ", "_");
		mp3FileName = MP3_RESOURCES_SUB_DIR + mp3FileName;

		AudioClip mp3Clip;

		yield return StartCoroutine(loadAudioFile("File:/" + mp3FileName + MP3_FILE_EXTENSION, value => mp3Clip = value));
	}
	IEnumerator loadAudioFile(string url, System.Action<AudioClip> result)
	{
		WWW www = new WWW(url);
		float elapsedTime = 0.0f;
		
		while (!www.isDone)
		{
			elapsedTime += Time.deltaTime;
			if (elapsedTime >= 10.0f) break;
			yield return null;
		}
		
		if (!www.isDone || !string.IsNullOrEmpty(www.error))
		{
			Debug.LogError("Load Failed");
			result(null);    // Pass null result.
			yield break;
		}
		
		result(www.audioClip); // Pass retrieved result.
	}

Problem is obviously, that GetAudiClip must be of type IEnumerator, but then I can’t return the value to the calling function. Is there any way around this?

1 Answer

1

private IEnumerator LoadAudio(string audioName, int track_id, float start_time)
{

        using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(
                                        musicPath.Replace("#","%23") + 
                                        
                                        audioName, AudioType.OGGVORBIS))
        {
            
            var synRes = www.SendWebRequest();
            yield return synRes;

            if (www.isNetworkError)
            {
                Debug.Log(www.error);
            }
            else
            {
                stream_music = DownloadHandlerAudioClip.GetContent(www);
                musicSource.clip = stream_music;
                musicSource.time = start_time;
                current_track_num = track_id;
                current_track = GetCurrentTrack();
                musicSource.Play();
            }
        }

    }