嗨,我有这个代码,假设转换csv文件到wav文件。它创建了一个wav文件,但我们什么也听不到。如果我把10行的csv文件,它使一个约1分钟的wav文件!所以这根本不成比例。
我的CSV看起来像:
0.000785,0.30886552
0.00157,0.587527526
0.002355,0.808736061
0.00314,0.950859461
0.003925,0.999999683
0.00471,0.951351376
0.005495,0.809671788
0.00628,0.588815562
0.007065,0.31037991
0.00785,0.001592653
0.008635,-0.307350347
0.00942,-0.586237999
0.010205,-0.807798281
0.01099,-0.950365133
0.011775,-0.999997146
0.01256,-0.951840879
0.013345,-0.810605462
0.01413,-0.590102105
0.014915,-0.311893512
0.0157,-0.003185302
0.016485,0.305834394
0.01727,0.584946986
0.018055,0.806858453
0.01884,0.949868395
0.019625,0.999992073
0.02041,0.952327967
0.021195,0.81153708
0.02198,0.591387151
0.022765,0.313406323
这里的代码:
#!/usr/bin/python
import wave
import numpy
import struct
import sys
import csv
import resampy
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))
#print("Please be patient while the file is written")
frames = []
for s in data:
mul = int(s * amplitude)
# print "s: %f mul: %d" % (s, mul)
frames.append(struct.pack('h', mul))
#frames = (struct.pack('h', int(s*self.amp)) for s in sine_list)
frames = ''.join(frames)
#for x in xrange(0, 7200):
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))
except ValueError:
pass # Just skip it
print("This is data lenght: %d" %(len(data)))
arr = numpy.array(data)
print arr
# Normalize data
arr /= numpy.max(numpy.abs(data))
print arr
filename_head, extension = fname.rsplit(".", 1)
# Resample normalized data to 8000 kHz
target_samplerate = 8000
sampled = resampy.resample(arr, target_samplerate/100000.0,16000)
#print sampled
write_wav(sampled, "new" + ".wav", target_samplerate, 32700)
print ("File written succesfully !")
原始代码来自github -普雷茨,并在google上看到了一些修正。
感谢所有
3条答案
按热度按时间11dmarpk1#
解决了!这里是将CSV文件转换为WAV文件的代码。CSV文件必须包含2列:第一个是样本的时间-在这个文件中它不重要,所以你可以把0到所有这一列。第二列是样本本身-例如,如果您的样本是16位长度-样本应该在-32678和32767之间(整数范围)。在第56行中,该数字将在-1和1之间归一化。在有了这个文件之后,你只需要运行.py,把csv文件的文件名作为参数。(如python generate.py sinewave.csv)。
好好享受吧!
ktecyv1j2#
使用pysoundfile
7d7tgy0s3#
谢谢khornlund,你的代码帮助.我还必须规范化数据,以便正确播放: