• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Jeff-Kesselman · Jun 28, 2014 at 07:06 PM · audiomemorydatawav

WAV byte[] to AudioClip?

I have a byte[] in memory that is the contents of a WAV file. I want to convert it to an AudioClip without going through the intermediary of writing and reading a WAV file on disk.

This seems it aught to be easy but I am having trouble finding the right magic words.

If someone can point me at the right methods in the docs or examples I'd appreciate it.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
11
Best Answer

Answer by Jeff-Kesselman · Jun 29, 2014 at 01:27 AM

Okay, I ended up finding some WAV parsing code and modifying it for my needs. If anyoen else needs it, here it is...

 using UnityEngine;
 using System.Collections;
 using System.IO;
 
 namespace WWUtils.Audio {
     public class WAV  {
 
         // convert two bytes to one float in the range -1 to 1
         static float bytesToFloat(byte firstByte, byte secondByte) {
             // convert two bytes to one short (little endian)
             short s = (short)((secondByte << 8) | firstByte);
             // convert to range from -1 to (just below) 1
             return s / 32768.0F;
         }
 
         static int bytesToInt(byte[] bytes,int offset=0){
             int value=0;
             for(int i=0;i<4;i++){
                 value |= ((int)bytes[offset+i])<<(i*8);
             }
             return value;
         }
 
         private static byte[] GetBytes(string filename){
             return File.ReadAllBytes(filename);
         }
         // properties
         public float[] LeftChannel{get; internal set;}
         public float[] RightChannel{get; internal set;}
         public int ChannelCount {get;internal set;}
         public int SampleCount {get;internal set;}
         public int Frequency {get;internal set;}
         
         // Returns left and right double arrays. 'right' will be null if sound is mono.
         public WAV(string filename):
             this(GetBytes(filename)) {}
 
         public WAV(byte[] wav){
             
             // Determine if mono or stereo
             ChannelCount = wav[22];     // Forget byte 23 as 99.999% of WAVs are 1 or 2 channels
 
             // Get the frequency
             Frequency = bytesToInt(wav,24);
             
             // Get past all the other sub chunks to get to the data subchunk:
             int pos = 12;   // First Subchunk ID from 12 to 16
             
             // Keep iterating until we find the data chunk (i.e. 64 61 74 61 ...... (i.e. 100 97 116 97 in decimal))
             while(!(wav[pos]==100 && wav[pos+1]==97 && wav[pos+2]==116 && wav[pos+3]==97)) {
                 pos += 4;
                 int chunkSize = wav[pos] + wav[pos + 1] * 256 + wav[pos + 2] * 65536 + wav[pos + 3] * 16777216;
                 pos += 4 + chunkSize;
             }
             pos += 8;
             
             // Pos is now positioned to start of actual sound data.
             SampleCount = (wav.Length - pos)/2;     // 2 bytes per sample (16 bit sound mono)
             if (ChannelCount == 2) SampleCount /= 2;        // 4 bytes per sample (16 bit stereo)
             
             // Allocate memory (right will be null if only mono sound)
             LeftChannel = new float[SampleCount];
             if (ChannelCount == 2) RightChannel = new float[SampleCount];
             else RightChannel = null;
             
             // Write to double array/s:
             int i=0;
             while (pos < wav.Length) {
                 LeftChannel[i] = bytesToFloat(wav[pos], wav[pos + 1]);
                 pos += 2;
                 if (ChannelCount == 2) {
                     RightChannel[i] = bytesToFloat(wav[pos], wav[pos + 1]);
                     pos += 2;
                 }
                 i++;
             }
         }
 
         public override string ToString ()
         {
             return string.Format ("[WAV: LeftChannel={0}, RightChannel={1}, ChannelCount={2}, SampleCount={3}, Frequency={4}]", LeftChannel, RightChannel, ChannelCount, SampleCount, Frequency);
         }
     }
 
 }


An example of its use:

 WAV wav = new WAV(rawData);
 Debug.Log(wav);
 AudioClip audioClip = AudioClip.Create("testSound", wav.SampleCount, 1,wav.Frequency, false, false);
 audioClip.SetData(wav.LeftChannel, 0);
 audio.clip = audioClip;
 audio.Play();
Comment
Add comment · Show 8 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Jack-Does · May 04, 2015 at 07:23 PM 0
Share

i know its a little late but would you mind posting a more specific way to use this?

avatar image lllzm · Jul 08, 2015 at 06:09 AM 0
Share

it works, thanks

avatar image SmallSage · Nov 30, 2016 at 02:47 AM 1
Share

Thanks,bug i find a bug, occur in the code line 68,I think should be changed to: while (i < SampleCount) ,Because array index is out of range by line 69.

avatar image Bunny83 SmallSage · Nov 30, 2016 at 03:43 AM 0
Share

To really be on the save side you could use

 int maxInput = wav.Length - (RightChannel == null)?1:3;
 while (i < SampleCount && pos < maxInput) {

Since both could potentially give you problems.

avatar image mikrima · Aug 01, 2018 at 08:34 PM 0
Share

Works like a charm, thousand thanks for this!

avatar image ModLunar · Aug 01, 2018 at 11:41 PM 0
Share

Wow this is really impressive, thanks so much for sharing this :o

Show more comments
avatar image
4

Answer by deadlyfingers · Jan 13, 2017 at 01:36 PM

I created a Wav Utility for Unity to convert wav bytes to AudioClip - https://github.com/deadlyfingers/UnityWav

You can pass wav byte[] array or just pass local file path using Application.persistentDataPath or Application.dataPath

 string path = string.Format ("{0}/{1}", Application.persistentDataPath, "recording.wav");
 AudioClip audioClip = WavUtility.ToAudioClip (path);
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by jemonsuarez · Jun 04, 2019 at 09:00 AM

Here is my solution for WAV files, it allows to convert from PCM byte arrays to AudioClip, and also from AudioClip to PCM file. OpenWavParser is free.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

30 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

calling www to get audio.clip multiple times causes memory problems 1 Answer

Unity says audio does not contain wav format? 0 Answers

Unity Audio Output Data 0 Answers

When is audio file loaded to memory 0 Answers

Music gapless looping doesn't work 1 Answer

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges