- Home /
How can I load an m4a file into an AudioClip?
Hello, I am currently working on loading an m4a file on the user's hard drive (not in the project or Resources folders) at runtime and having an AudioClip play the file. I know that just using WWW is not supported, and I previously got around the MP3 loading limitations by using the NAudio library to read in the data stream and convert it to a wav before sending it to the AudioClip. I have tried to replicate this with loading m4a files but have hit a bit of a road block. I have tried two different methods but in both cases Unity will just crash and I really don't know why. Here are the two methods I'm using:
public static AudioClip FromM4aFile(string filepath)
{
// create media foundation reader to read the AAC encoded file
MediaFoundationReader reader = new MediaFoundationReader(filepath);
// resample the file to PCM with same sample rate, channels and bits per sample
ResamplerDmoStream resampledReader = new ResamplerDmoStream(reader,
new WaveFormat(reader.WaveFormat.SampleRate, reader.WaveFormat.BitsPerSample, reader.WaveFormat.Channels));
WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(resampledReader);
// Convert to WAV data
WAV wav = new WAV(AudioMemStream(waveStream).ToArray());
Debug.Log(wav);
AudioClip audioClip = AudioClip.Create("testSound", wav.SampleCount, 1,wav.Frequency, false);
audioClip.SetData(wav.LeftChannel, 0);
// Return the clip
return audioClip;
}
and
public static AudioClip FromM4aData(byte[] data)
{
// Load the data into a stream
MemoryStream m4astream = new MemoryStream(data);
// Convert the data in the stream to WAV format
StreamMediaFoundationReader m4aAudio = new StreamMediaFoundationReader(m4astream);
WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(m4aAudio);
// Convert to WAV data
WAV wav = new WAV(AudioMemStream(waveStream).ToArray());
Debug.Log(wav);
AudioClip audioClip = AudioClip.Create("testSound", wav.SampleCount, 1,wav.Frequency, false);
audioClip.SetData(wav.LeftChannel, 0);
// Return the clip
return audioClip;
}
If anyone knows why Unity is crashing or any other way I can dynamically load an m4a file I would greatly appreciate the help!
Thanks! ~ Ceraph
Your answer
Follow this Question
Related Questions
How do I load an audio file from persistantdatapath? 0 Answers
Loading external audio 1 Answer
Is there a way to create a random Audiosource loop? 2 Answers
Sound creation using WAV. files 1 Answer
Problem with enabling and playing audios 0 Answers