本文整理汇总了Python中wave.open函数的典型用法代码示例。如果您正苦于以下问题:Python open函数的具体用法?Python open怎么用?Python open使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了open函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: pack2
def pack2(self):
if self.width2==1:
fmt="%iB" % self.frames2*self.channel2
else:
fmt="%ih" % self.frames2*self.channel2
out=struct.pack(fmt,*(self.new2))
if self.pl2==0 or self.pl2==3:
out_file=wave.open("ampli2.wav",'w')
elif self.pl2==1:
out_file=wave.open("wave_mix2.wav",'w')
elif self.pl2==2:
out_file=wave.open("wave_mod2.wav",'w')
out_file.setframerate(self.rate2)
out_file.setnframes(self.frames2)
out_file.setsampwidth(self.width2)
out_file.setnchannels(self.channel2)
out_file.writeframes(out)
out_file.close()
if self.pl2==0:
self.read_new("ampli2.wav",1)
elif self.pl2==1:
self.read_new("wave_mix2.wav",4)
self.pl2=0
elif self.pl2==2:
self.read_new("wave_mod2.wav",3)
self.pl2=0
else:
self.pl2=0
示例2: splitSong
def splitSong(inputSongName, inputSongFolder, outputSongFolder):
inputSongFileNameNoExt = os.path.splitext(inputSongName)[0]
waveExtension = ".wav"
inputSongFileName = inputSongFolder+'//'+inputSongName
segmentLengthInSeconds = 10;
try:
waveInput = wave.open(inputSongFileName, 'rb')
totalNumberOfFrames = waveInput.getnframes()
frameRate = waveInput.getframerate()
segmentLengthInFrames = (frameRate * segmentLengthInSeconds)-((frameRate * segmentLengthInSeconds)%1024)
numberOfSegments = int(float(totalNumberOfFrames)/segmentLengthInFrames)
#print segmentLengthInFrames
for i in xrange(numberOfSegments):
outputSegmentFileName = outputSongFolder+'//'+inputSongFileNameNoExt + "_part" + str(i) + waveExtension
waveOutput = wave.open(outputSegmentFileName, 'wb')
waveOutput.setparams(waveInput.getparams())
frames = waveInput.readframes(segmentLengthInFrames) # read 10s of input
waveOutput.writeframes(frames) # write 10 s to output segment
waveOutput.close
waveInput.close()
except EOFError as e:
print e
#splitSong("testSong.wav", "//home//christophe//IdeaProjects//GenreClassificationScripts//truncateSong//TestFolderOutput")
示例3: noisered
def noisered(fname):
wr = wave.open(fname, 'r')
par = list(wr.getparams())
par[3] = 0
ww = wave.open('filtered-talk.wav', 'w')
ww.setparams(tuple(par))
lowpass = 200
highpass = 6000
sz = wr.getframerate()
c = int(wr.getnframes()/sz)
for num in range(c):
da = np.fromstring(wr.readframes(sz), dtype=np.int16)
left, right = da[0::2], da[1::2]
lf, rf = np.fft.rfft(left), np.fft.rfft(right)
lf[:lowpass], rf[:lowpass] = 0, 0
lf[55:66], rf[55:66] = 0, 0
lf[highpass:], rf[highpass:] = 0,0
nl, nr = np.fft.irfft(lf), np.fft.irfft(rf)
ns = np.column_stack((nl,nr)).ravel().astype(np.int16)
ww.writeframes(ns.tostring())
wr.close()
ww.close()
fname='filtered-talk.wav'
sptotex(fname)
示例4: split_wav_file
def split_wav_file(filename, part_length, dest_dir=None, basename=None):
"""
@brief: splits a wav file into smaller
@param filename: the name of the file
@param part_length: the length in seconds of each part
@param dest_dir: the directory in which all parts should be. default is current directory
@param basename: the name of the output files. they will be called <basename>_00000.wav
@note: the maxium original file length is 833 hours
"""
if dest_dir is None:
dest_dir = '.'
if basename is None:
basename = os.path.basename(filename)
original_file = wave.open(filename, 'r')
file_params = original_file.getparams()
number_of_frames_per_part = int(original_file.getframerate() * part_length)
total_number_of_frames = file_params[3]
file_counter = 0
data = 'init'
while len(data) != 0:
new_filename = basename + '_' + '0' * (DIGITS_IN_NAME-len(str(file_counter))) + str(file_counter) + '.wav'
current_file = wave.open(os.path.join(dest_dir, new_filename), 'w')
current_file.setparams(file_params)
data = original_file.readframes(number_of_frames_per_part)
total_number_of_frames -= number_of_frames_per_part
current_file.writeframes(data)
current_file.close()
file_counter += 1
original_file.close()
示例5: main
def main():
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
lengthbuf = recvall(conn, 4)
length, = struct.unpack('!I', lengthbuf)
data = recvall(conn, length)
output_framelist = pickle.loads(data)
#conn.close()
ifile = wave.open("../files/9.wav","r")
ofile = wave.open("../files/noise.wav", "w")
ofile.setparams(ifile.getparams())
sampwidth = ifile.getsampwidth()
fmts = (None, "=B", "=h", None, "=l")
fmt = fmts[sampwidth]
dcs = (None, 128, 0, None, 0)
dc = dcs[sampwidth]
for iframe in output_framelist:
oframe = iframe / 2;
oframe += dc
oframe = struct.pack(fmt, oframe)
ofile.writeframes(oframe)
ifile.close()
ofile.close()
示例6: buildFileWav
def buildFileWav(infiles, files_dir):
import wave
outfile = os.path.join(files_dir,OUTPUT_FILENAME_WAV)
data= []
wav_frames_total = 0
for infile in infiles:
log(infile)
w = wave.open(infile, 'rb')
wav_frames_total += w.getnframes()
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
output = wave.open(outfile, 'wb')
log(data[0][0])
output.setparams(data[0][0])
# On older (buggy?) Python versions like XBMC's built-in 2.4 .writeframes() seems not to update the "nframes" field of the WAV header
# and the resulting output file is a truncated mess. Therefore, force the nframes for the header and only write raw data.
#
# To give developers even more fun, trying to manually build the full header on python 2.4 is an epic fail:
# - when you read the docs for wave module (python 2.4 and all next versions) it says .setcomptype() takes 2 parameters;
# - when you call .readcomptype() you get a list of two elements;
# - when you feed this list to .setcomptype(), it raises an error that it takes "exactly 3 parameters"!
#
# On a modern Python version, just skip the .setnframes() and inside the loop, call .writeframes() instead of .writeframesraw()
output.setnframes(wav_frames_total)
for i in range(0, 32):
output.writeframesraw(data[i][1])
output.close()
return outfile
示例7: int
def 切割音檔(被切音檔路徑, 完成音檔指標, 開頭時間, 結尾時間):
# 切割一份字格中的一個漢字產生一個音檔
origAudio = wave.open(被切音檔路徑,'r')
frameRate = origAudio.getframerate()
nChannels = origAudio.getnchannels()
sampWidth = origAudio.getsampwidth()
nFrames = origAudio.getnframes()
# 0.2和0.1是隨便給的
start = int((float(開頭時間) - 0.05)*frameRate)
end = int((float(結尾時間) + 0.01)*frameRate)
# 確認切割位置:若是輸入的切割位置超出了音檔的長度,就切齊。
if(start < 0):
start = 0
if(end > nFrames):
end = nFrames
anchor = origAudio.tell()
origAudio.setpos(anchor + start)
chunkData = origAudio.readframes(end-start)
# 輸出:存出音檔
chunkAudio = wave.open(完成音檔指標,'w')
chunkAudio.setnchannels(nChannels)
chunkAudio.setsampwidth(sampWidth)
chunkAudio.setframerate(frameRate)
chunkAudio.writeframes(chunkData)
chunkAudio.close()
origAudio.close()
示例8: _locate_and_modify_sounds
def _locate_and_modify_sounds(self, n_sounds):
"""Find wum samples and preload them as streams"""
sounds = []
for speed in range(1, n_sounds+1): # speed 0 = no sound
filename = os.path.join(self.config['samples'], 'wum' + str(speed) + '.wav')
print(filename)
original_wave = wave.open(filename, 'rb')
original_stream = original_wave.readframes(self.FRAME_RATE * self.FRAME_DURATION)
volumes = []
for volume in range(1, self.MAX_VOLUME + 1):
print("building volume", volume)
fmt = 'h' * (self.FRAME_RATE * self.FRAME_DURATION)
values = struct.unpack(fmt, original_stream)
values = map(lambda sample: int(float(sample) * (float(volume) / self.MAX_VOLUME)) , values)
data_chunk_modified = struct.pack(fmt, *values)
modified_stream = io.BytesIO()
modified_wave = wave.open(modified_stream, 'w')
modified_wave.setparams((self.CHANNELS, self.BPS, self.FRAME_RATE, self.FRAME_RATE * self.FRAME_DURATION, "NONE", "Uncompressed"))
modified_wave.writeframes(data_chunk_modified)
modified_wave.close()
modified_stream.seek(0)
volumes.append(wave.open(modified_stream, 'rb'))
sounds.append(volumes)
#TODO: fail gracefully if a sample is missing
original_wave.close()
return sounds
示例9: decrypt
def decrypt(key, cipherfile, decryptfile):
if cipherfile.endswith('.wav'):
# Wave file open
waveRead = wave.open(cipherfile, 'rb')
waveWrite = wave.open(decryptfile, 'wb')
# Reads the parameters
header = waveRead.getparams()
frames = waveRead.getnframes()
sampleWidth = waveRead.getsampwidth()
assert(waveRead.getnchannels() == 1)
ciphertext = [byte for byte in waveRead.readframes(frames)]
plaintext = bytearray([x for x in crypt(key, ciphertext)])
# Writes the parameters and data to wave
waveWrite.setparams(header)
waveWrite.setnchannels(1)
waveWrite.setsampwidth(sampleWidth)
waveWrite.writeframes(plaintext)
waveRead.close()
waveWrite.close()
else:
# Regular file
with open(cipherfile) as cipherTextFile:
with open(decryptfile, mode='w') as plainTextFile:
ciphertext=cipherTextFile.read()
plaintext = ''.join(crypt(key, ciphertext))
plainTextFile.write(plaintext)
示例10: add_wav
def add_wav(self,files,read=False) :
"files : filename, filename , ...]"
# read all files in memory (not too big) and append to chip
assert files,'nothing to write'
for f in files : # check all BEFORE actual writing
fp_in = wave.open(f)
print >>sys.stderr,fp_in.getnchannels(), "channels"
assert fp_in.getnchannels()!='1',"mono sound file only !"
print >>sys.stderr,fp_in.getsampwidth(), "byte width"
assert fp_in.getsampwidth()==1,'only 8 bits input !'
print >>sys.stderr,fp_in.getframerate(), "samples per second"
assert fp_in.getframerate()==8000,'only 8khz samplerate !'
self.read_table()
for f in files :
print >>sys.stderr,'Adding ',f,'...'
# read input entirely into memory
fp_in = wave.open(f, "r")
frameraw = fp_in.readframes(fp_in.getnframes())
# append / prepend ramping sound to avoid clicks
pre = ''.join([chr(i) for i in range(0,ord(frameraw[0]),16)])
post = ''.join([chr(i) for i in range(ord(frameraw[-1]),0,-16)])
self.write(f,pre+frameraw+post,read)
self.write_table()
示例11: wavSamplesNextFrame
def wavSamplesNextFrame(wavFile=None, chunk=None, overlap=None):
#read a frame from wave file back as float numpy array, each index is a channel
#can give chunk/overlap/wavfile name on first call and all is stored in function
if wavSamplesNextFrame.w is None:
if wavFile is None:
sys.exit( "ERROR: must specify WAV FILE!!" )
return
wavSamplesNextFrame.w = wave.open(wavFile, 'r')
wavSamplesNextFrame.name = wavFile
if wavFile is not None:
if (wavFile != wavSamplesNextFrame.name):
wavSamplesNextFrame.w.close()
wavSamplesNextFrame.w = wave.open(wavFile, 'r')
wavSamplesNextFrame.name = wavFile
if chunk is not None:
wavSamplesNextFrame.chunk = chunk
if overlap is not None:
wavSamplesNextFrame.overlap = overlap
#set pointer to wav based on overlap
currentPos = wavSamplesNextFrame.w.tell()
if (currentPos > wavSamplesNextFrame.overlap):
wavSamplesNextFrame.w.setpos(currentPos - wavSamplesNextFrame.overlap)
#read chunk as string
astr = wavSamplesNextFrame.w.readframes(wavSamplesNextFrame.chunk)
# convert binary chunks to short
a = struct.unpack("%ih" % (wavSamplesNextFrame.chunk* wavSamplesNextFrame.w.getnchannels()), astr)
a = [float(val) / pow(2, 15) for val in a]
#make into numpy array by channel
anew = []
for ind in range(wavSamplesNextFrame.w.getnchannels()):
anew.append(a[ind::wavSamplesNextFrame.w.getnchannels()])
return np.array(anew)
示例12: slice_wave
def slice_wave(in_file, out_file, offset=0, duration=0, max_framerate=None):
"""Write a section of a wavefile to a new file"""
with closing(wave.open(in_file)) as win:
params = win.getparams()
wav = wave.open(out_file, 'wb')
try:
if not max_framerate:
frames, params = _get_frames(in_file, offset, duration)
else:
audio, framerate = get_audio(in_file, offset=offset, duration=duration, max_framerate=max_framerate)
params = list(params)
if len(audio.shape) == 1:
params[0] = 1
else:
params[0] = audio.shape[1]
params[2] = framerate
audio = audio.flatten() + _zeroline[params[1]]
frames = struct.pack(_formats[params[1]] % (len(audio),), *audio)
wav.setparams(params)
wav.writeframes(frames)
finally:
try:
wav.close()
except:
pass
示例13: crop_wav
def crop_wav(split_start, split_end, input_file_name, output_file_name):
print("splitting")
mydir = os.getcwd()
input_file_path = mydir + "/" + input_file_name
output_file_path = mydir + "/" + output_file_name
input_file = wave.open(input_file_path, 'r')
width = input_file.getsampwidth()
rate = input_file.getframerate()
fpms = rate / 1000 # frames per ms
#programmatically figure out start and end split
length = (split_end - split_start) * fpms
start_index = split_start * fpms
# os.mkdir(path)
output_file = wave.open(output_file_path, "w")
output_file.setparams((input_file.getnchannels(), width, rate, length, input_file.getcomptype(), input_file.getcompname()))
input_file.rewind()
anchor = input_file.tell()
input_file.setpos(anchor + start_index)
output_file.writeframes(input_file.readframes(length))
input_file.close()
output_file.close()
print("finished split")
示例14: pack3
def pack3(self):
if self.width3==1:
fmt="%iB" % self.frames3*self.channel3
else:
fmt="%ih" % self.frames3*self.channel3
out=struct.pack(fmt,*(self.new3))
if self.pl3==0 or self.pl3==3:
out_file=wave.open("ampli3.wav",'w')
elif self.pl3==1:
out_file=wave.open("wave_mix3.wav",'w')
elif self.pl3==2:
out_file=wave.open("wave_mod3.wav",'w')
print self.pl3
out_file.setframerate(self.rate3)
out_file.setnframes(self.frames3)
out_file.setsampwidth(self.width3)
out_file.setnchannels(self.channel3)
out_file.writeframes(out)
out_file.close()
if self.pl3==0 :
self.read_new("ampli3.wav",2)
elif self.pl3==1:
self.read_new("wave_mix3.wav",4)
self.pl3=0
elif self.pl3==2:
self.read_new("wave_mod3.wav",3)
self.pl3=0
else:
self.pl3=0
示例15: mix_files
def mix_files(a, b, c, chann=2, phase=-1.0):
f1 = wave.open(a, "r")
f2 = wave.open(b, "r")
f3 = wave.open(c, "w")
f3.setnchannels(chann)
f3.setsampwidth(2)
f3.setframerate(44100)
f3.setcomptype("NONE", "Not Compressed")
frames = min(f1.getnframes(), f2.getnframes())
print "Mixing files, total length %.2f s..." % (frames / 44100.0)
d1 = f1.readframes(frames)
d2 = f2.readframes(frames)
for n in range(frames):
if not n % (5 * 44100):
print n // 44100, "s"
if chann < 2:
d3 = struct.pack(
"h", 0.5 * (struct.unpack("h", d1[2 * n : 2 * n + 2])[0] + struct.unpack("h", d2[2 * n : 2 * n + 2])[0])
)
else:
d3 = struct.pack(
"h",
phase * 0.3 * struct.unpack("h", d1[2 * n : 2 * n + 2])[0]
+ 0.7 * struct.unpack("h", d2[2 * n : 2 * n + 2])[0],
) + struct.pack(
"h",
0.7 * struct.unpack("h", d1[2 * n : 2 * n + 2])[0]
+ phase * 0.3 * struct.unpack("h", d2[2 * n : 2 * n + 2])[0],
)
f3.writeframesraw(d3)
f3.close()