Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question how to set mp3 audio file from local storage to audio clip in audio source component .

Discussion in 'Audio & Video' started by unity_C74DC6497F50958E9BEF, Sep 14, 2023.

  1. unity_C74DC6497F50958E9BEF

    unity_C74DC6497F50958E9BEF

    Joined:
    Aug 5, 2023
    Posts:
    5
    how to set mp3 audio file from local storage to audio clip in audio source component at runtime.
     
  2. SeventhString

    SeventhString

    Unity Technologies

    Joined:
    Jan 12, 2023
    Posts:
    290
    Hi,

    You can use web requests for that.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.Networking;
    3. using System.Collections;
    4.  
    5. public class MP3Loader : MonoBehaviour
    6. {
    7.     public AudioSource audioSource;
    8.     private string path;
    9.  
    10.     private void Start()
    11.     {
    12.         path = "YOUR_LOCAL_PATH_TO_MP3"; // e.g., "file:///C:/path/to/your/file.mp3"
    13.         StartCoroutine(LoadAudio());
    14.     }
    15.  
    16.     IEnumerator LoadAudio()
    17.     {
    18.         using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(path, AudioType.MPEG))
    19.         {
    20.             yield return www.SendWebRequest();
    21.  
    22.             if (www.result == UnityWebRequest.Result.ConnectionError)
    23.             {
    24.                 Debug.LogError("Error while loading audio: " + www.error);
    25.             }
    26.             else
    27.             {
    28.                 AudioClip clip = DownloadHandlerAudioClip.GetContent(www);
    29.                 audioSource.clip = clip;
    30.                 audioSource.Play();
    31.             }
    32.         }
    33.     }
    34. }
    35.