Csv To Wav Python
Hi i have this code that suppose to convert csv file to wav file. it creates a wav file but we don't hear anything. If i put 10 rows in the csv file, it make an about 1 min wav fil
Solution 1:
RESOLVED ! Here the code for converting a CSV file in a WAV file. The CSV file must have 2 columns: The first is the time of the sample - in this file it doesn't matter so you can put 0 to all this column. The second column is the sample itself - for example if your sample is 16 bit length - the sample should be between -32678 and 32767 ( int range ). This number will be normalize between -1 and 1 in line 56. After the have this file you just have to run the .py with the filename of the csv file as an argument. ( like python generate.py sinewave.csv ).
#!/usr/bin/python
import wave
import struct
import sys
import csv
import numpy
from scipy.io import wavfile
from scipy.signal import resample
def write_wav(data, filename, framerate, amplitude):
wavfile = wave.open(filename,'w')
nchannels = 1
sampwidth = 2
framerate = framerate
nframes = len(data)
comptype = "NONE"
compname = "not compressed"
wavfile.setparams((nchannels,
sampwidth,
framerate,
nframes,
comptype,
compname))
frames = []
for s in data:
mul = int(s * amplitude)
frames.append(struct.pack('h', mul))
frames = ''.join(frames)
wavfile.writeframes(frames)
wavfile.close()
print("%s written" %(filename))
if __name__ == "__main__":
if len(sys.argv) <= 1:
print ("You must supply a filename to generate")
exit(-1)
for fname in sys.argv[1:]:
data = []
for time, value in csv.reader(open(fname, 'U'), delimiter=','):
try:
data.append(float(value))#Here you can see that the time column is skipped
except ValueError:
pass # Just skip it
arr = numpy.array(data)#Just organize all your samples into an array
# Normalize data
arr /= numpy.max(numpy.abs(data)) #Divide all your samples by the max sample value
filename_head, extension = fname.rsplit(".", 1)
data_resampled = resample( arr, len(data) )
wavfile.write('rec.wav', 16000, data_resampled) #resampling at 16khz
print ("File written succesfully !")
Enjoy !
CSV example:
0 , 20
0 , 15
0 , -40
0 , -1000
...
Solution 2:
Use pysoundfile
import pandas as pd
import soundfile as sf
# assume we have columns 'time' and 'value'
df = pd.read_csv('recording.csv')
# compute sample rate, assuming times are in seconds
times = df['time'].values
n_measurements = len(times)
timespan_seconds = times[-1] - times[0]
sample_rate_hz = int(n_measurements / timespan_seconds)
# write data
data = df['value'].values
sf.write('recording.wav', data, sample_rate_hz)
Post a Comment for "Csv To Wav Python"