Search code examples
c#unity-game-engineaudioclip

how to connect AudioClip at local file


I downloaded the .mp3 file from the server and stored it in my android persistentDataPath. But I do not know how to connect .mp3 files to AudioClip. Please let me know if there is a workaround for this.


Solution

  • Update

    As pointed out in the comments WWW now supports .mp3 files making it the way to go.

    using UnityEngine;
    using System.Collections;
    
    public class ExampleClass : MonoBehaviour {
        public string url;
        public AudioSource source;
        void Start() {
            WWW www = new WWW(url);
            source = GetComponent<AudioSource>();
            source.clip = www.audioClip;
        }
        void Update() {
            if (!source.isPlaying && source.clip.isReadyToPlay)
                source.Play();
    
        }
    }
    

    Original answer:

    Audio clip doesn't accept a file. It accepts an array of floats.

    You can use NAudio to convert the compressed MP3 to a WAV file.

    using NAudio;
    using NAudio.Wave;
    // ....
    
    using (Mp3FileReader reader = new Mp3FileReader(mp3File))
    {
        WaveFileWriter.CreateWaveFile(outputFile, reader);
    }
    

    You will then need to read the wave file which will basically have a header followed by the chunk data. The chunk data can be converted to a float and sent to your audio clip.