Skip to content

Instantly share code, notes, and snippets.

@cabbibo
Created February 20, 2018 23:13
Show Gist options
  • Save cabbibo/24457ace2aba287869f89739af888e26 to your computer and use it in GitHub Desktop.
Save cabbibo/24457ace2aba287869f89739af888e26 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class CaptureAudioTexture : MonoBehaviour {
private int width;
private int height; // ABOUT 60 FPS
public string savePath;
[System.Serializable]
public class Data{
public float[] timeStamps;
public float[] data;
}
private Data data;
private int currentFrame = 0;
private float fps;
private float[] samples;
private float oTime;
private float time;
public bool ended = false;
public bool startCapture=false;
public bool oStartCapture=false;
public float startTime;
public AudioSource audio;
public int sizePerFrame;
public Data GetData(){ return data; }
// Use this for initialization
void Awake() {
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = 60;
width = 1024;
sizePerFrame = 1024 * 8;
height =(int)(( audio.clip.length + 4 ) * 60);
samples = new float[sizePerFrame];
data = new Data();
data.data = new float[height*sizePerFrame];
data.timeStamps = new float[height];
// loadDataFromDisk();
}
void EndIt(){
ended = true;
saveDataToDisk();
}
public void saveDataToDisk(){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(savePath);
bf.Serialize(file, data);
file.Close();
}
public void loadDataFromDisk(){
if(File.Exists(savePath)){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(savePath, FileMode.Open);
data = (Data)bf.Deserialize(file);
file.Close();
}else{
print("NODATA");
}
}
// Update is called once per frame
void Update () {
if( oStartCapture == false && startCapture == true ){
audio.Play();
currentFrame = 0;
startTime = Time.time;
}
if( time > audio.clip.length ){
startCapture = false;
EndIt();
print( "ended");
print( currentFrame );
print( time * 60 );
}
if( startCapture == true ){
//print( currentFrame );
time = Time.time - startTime;
data.timeStamps[currentFrame] = time;
AudioListener.GetSpectrumData(samples, 0, FFTWindow.BlackmanHarris);
for( int i = 0; i< sizePerFrame; i++){
data.data[currentFrame*sizePerFrame + i] = samples[i];
}
float d = time - oTime;
currentFrame ++;
}
oStartCapture = startCapture;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment