Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Create an AudioClip in runtime

Discussion in 'Scripting' started by Simon75012, Feb 6, 2019.

  1. Simon75012

    Simon75012

    Joined:
    Sep 15, 2016
    Posts:
    79
    Hi, i'd like to create an audio file in Runtime, made of other audioclip.

    Let's say i have 3 audio clip :
    1) 5 seconds audio (Voice saying "A")
    2) 4 sec audio (Voice saying "B")
    3) 4 sec audio (Voice saying "C")

    I want to create an audioclip with the 3 audioclip following each other, so a 13 seconds audioclip.

    I tried some dirty things like GetData on each audioclip and store it in a float array.
    Then create an Audioclip of the correct length and SetData with this array.

    The result of this clip is :
    -The length is correct (13 sec)
    -The audio clip just have the first "A" audioclip at the begining and then it's blank till the end...

    I think i'm almost there but i miss something...
    Each audioclip have the same frequency (44100) and channels (2)

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class createaudio : MonoBehaviour {
    6.     public AudioClip[] audios;
    7.     AudioSource audioSource;
    8.     // Use this for initialization
    9.     void Start () {
    10.         audioSource = GetComponent<AudioSource>();
    11.  
    12.         List<float[]> listData = new List<float[]>();
    13.         int iTotalSize = 0;
    14.         foreach (AudioClip audio in audios)
    15.         {
    16.             iTotalSize += audio.samples;
    17.         }
    18.         Debug.Log("Total size : " + iTotalSize);
    19.  
    20.         float[] fData = new float[iTotalSize];
    21.         int iNext = 0;
    22.         foreach ( AudioClip audio in audios){
    23.             float[] f = new float[audio.samples];
    24.             audio.GetData(f,0);
    25.             for (int k = 0; k < f.Length; k++ ){
    26.                 fData[iNext] = f[k];
    27.                 iNext++;
    28.             }
    29.         }
    30.         AudioClip clip = AudioClip.Create("TestAudioClip", iTotalSize, audios[0].channels, audios[0].frequency, false);
    31.         clip.SetData(fData, 0);
    32.         audioSource.clip = clip;
    33.         Debug.Log("Time : " + clip.length);
    34.     }
    35.  
    36. }
    37.  
    o_O
     
    Last edited: Feb 6, 2019