Unity에서 Float Binary File 만들기
유니티의 오디오 클립의 데이터를 float binary file로 저장하여 보도록 하자. 오디오 클립의 데이터는 다음과 같이 억세스 가능하다.
AudioSource goAudioSource = this.GetComponent<AudioSource>();
float[] samples = new float [goAudioSource.clip.samples * goAudioSource.clip.channels];
goAudioSource.clip.GetData(samples, 0);
for (int i = 0; i < samples.Length; ++i)
{
Debug.Log(samples[i]);
}
이를 바이너리 파일로 저장한다. 아래와 같은 코드를 사용하면 된다.
//using System.IO;
using (FileStream file = File.Create("data_float.dat"))
{
using (BinaryWriter writer = new BinaryWriter(file))
{
foreach (float value in samples)
{
writer.Write(value);
}
}
}
Python에서 float Binary File 읽기
Python에서 유니티에서 만든 파일(위의 예제)을 아래와 같이 읽을 수 있다. little-endian을 사용하였다.
import numpy as np
def readFloatBinaryFile():
f = open("data\_float.dat", 'rb')
#data = np.fromfile(f, '>f4') # big-endian float32
data = np.fromfile(f, '<f4') # little-endian float32
for fval in data:
print(fval)
f.close()
pass
numpy 라이브러리를 이용한 파일 입출력 예를 정리하여 보았다.
import numpy as np
def readNumpyFloatBinaryFile():
data = np.asarray([0.3, 1.4, 2.5, 3.6, 4.2, 5.2, 6.4, 7.8, 8.2, 9.2])
# save to csv file
np.savetxt('data.csv', data, delimiter=',')
# read from csv file
data2= np.loadtxt('data.csv', delimiter=',')
print("read from csv file")
print(data2)
#save as numpy binary
np.save('data.npy', data)
#read from numpy binary
data3 = np.load('data.npy')
print("read from binary file")
print(data3)
Python에서 float Binary File읽고 Plot하기
유니티에서 float binary 파일로 저장한 데이터를 읽어서 plot를 하여보자. 유니티에서 제대로 저장된 데이터인지 여부를 확인할 필요가 있다. 단순히 값을 읽어서 출력 만으로는 확인할 수가 없어서 그려본다. 테스트용 프로그램이라 최대한 간단하게 원리만 이용하여 프로그램을 작성하였다.
def drawWaveform():
import matplotlib.pyplot as plt
f = open("data_float.dat", 'rb')
#data = np.fromfile(f, '>f4') # big-endian float32
dataY = np.fromfile(f, '<f4') # little-endian float32
dataX=[]
count=0;
for fval in dataY:
print(fval)
dataX.append(count)
count=count+1
f.close()
# 1. draw waveform
plt.title('waveforms')
plt.xlabel('Samples')
plt.ylabel('Wave')
plt.plot(dataX,dataY)
plt.show()
pass
반응형