DomasG
DomasG

Reputation: 45

Playing AudioClip fetched from Resources folder

I need to fetch the audioClip in the resources folder so as I understand I need to use Resources.Load<AudioClip>(path) or Resources.Load(path) as AudioClip but this just doesn't work, it doesn't even return a null it just stops the code

my code sample:

private void FetchAudioClipAndStartPlay(int userPos, int index)
{


    AudioClip clip = Resources.Load($"Audio/Demo_ENG/D{userPos}a") as AudioClip;
    Debug.Log("Starting Coroutine " + index);
    StartCoroutine(PlayAudioClipAndStartRetrievingFromDatabase(index, clip));
}

IEnumerator PlayAudioClipAndStartRetrievingFromDatabase(int index, AudioClip clip)
{
    Debug.Log("Starting to play " + index);
    audioSource.PlayOneShot(clip, 1f);
    yield return new WaitForSeconds(clip.length);

    if (index < numberOfPlayers)
    {
        RetrieveFromDatabase(index++);
    }
}

(it doesn't enter the coroutine)

enter image description here

enter image description here

All the audio files are .mp3

Any guidance and tips are very appreciated!

Upvotes: 0

Views: 880

Answers (1)

aalmigthy
aalmigthy

Reputation: 1311

  1. Unity does not support loading mp3 at runtime.
  2. Unity does not recommend using the Resources folder:

Don't use it.
This strong recommendation is made for several reasons:

  • Use of the Resources folder makes fine-grained memory management more difficult Improper use of Resources folders will increase application startup time and the length of builds
  • As the number of Resources folders increases, management of the Assets within those folders becomes very difficult
  • The Resources system degrades a project's ability to deliver custom content to specific platforms and eliminates the possibility of incremental content upgrades AssetBundle Variants are Unity's primary tool for adjusting content on a per-device basis

Check this answer for a solution how to load audio files:

public void LoadSong()
{
    StartCoroutine(LoadSongCoroutine());    
}

IEnumerator LoadSongCoroutine()
{
    string url = string.Format("file://{0}", path); 
    WWW www = new WWW(url);
    yield return www;

    song.clip = www.GetAudioClip(false, false);
    songName =  song.clip.name;
    length = song.clip.length;
}

Upvotes: 2

Related Questions