将csv转换为wav python [英] csv to wav python

查看:313
本文介绍了将csv转换为wav python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,假设要将CSV文件转换为WAV文件. 它会创建一个wav文件,但我们听不到任何声音.如果我在csv文件中放入10行,它将产生大约1分钟的wav文件!因此它根本不成比例.

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 file ! So it is not proportional at all.

我的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-pretz,其中包含我在Google上看到的一些修复程序.

The original code is from github - pretz with some fixes i saw on google.

谢谢所有

推荐答案

已解决!这里是用于在WAV文件中转换CSV文件的代码. CSV文件必须具有2列: 第一个是采样时间-在此文件中没有关系,因此您可以在所有此列中输入0. 第二列是样本本身-例如,如果样本的长度为16位-样本应介于-32678和32767(int range)之间.此数字将在第56行的-1和1之间归一化. 在拥有此文件之后,您只需要使用csv文件的文件名作为参数运行.py. (例如python generate.py sinewave.csv).

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 !")

享受!

CSV example:
0 , 20
0 , 15
0 , -40
0 , -1000
...

这篇关于将csv转换为wav python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆