Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Unity 5 audio get/setData

Discussion in 'Audio & Video' started by jister, Mar 25, 2015.

  1. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    hey I had a unity 4 project where is could make a sample loop from a part of a playing audioclip.
    you choose which part by pressing space when you want your sample to start and release space for the end point. This basically made a new audioclip that looped.
    problem in 5 is that i can only use GetData and SetData in the audioclip is set to Decompress on load. which isn't good for big files. also the audioclip won't even start playing anymore if i set the file to Decompress on load... any idea how to fix this?
    here the code for it:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class BufferAudio : MonoBehaviour {
    5.  
    6.     //public int nrOfSamples = 3;
    7.     public AudioClip mySourceClip;
    8.     public AudioClip myAudioClip;
    9.     public float[] myBuffer;
    10.     public int bufferStart, bufferEnd;
    11.  
    12.     void Start()
    13.     {
    14.         if (!audio.playOnAwake)
    15.             audio.Play();
    16.     }
    17.     void FixedUpdate()
    18.     {
    19.         if(Input.GetKeyDown(KeyCode.Space))
    20.         {
    21.             bufferStart = audio.timeSamples;
    22.         }
    23.         if(Input.GetKeyUp(KeyCode.Space))
    24.         {
    25.             bufferEnd = audio.timeSamples;
    26.             myBuffer = new float[bufferStart+bufferEnd];
    27.             Debug.Log(myBuffer.Length);
    28.             myAudioClip = AudioClip.Create("MySinusoid", myBuffer.Length, mySourceClip.channels, mySourceClip.frequency, false, false);
    29.             audio.clip = myAudioClip;
    30.             mySourceClip.GetData(myBuffer, bufferStart);
    31.             myAudioClip.SetData(myBuffer, 0);
    32.             audio.Play();
    33.         }
    34.  
    35.     }
    36. }
    37.