• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python wave.open函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中wave.open函数的典型用法代码示例。如果您正苦于以下问题:Python open函数的具体用法?Python open怎么用?Python open使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了open函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:vivek425ster,项目名称:WaveMixer,代码行数:31,代码来源:201202182.py


示例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")
开发者ID:damianpolan,项目名称:Music-Genre-Classification,代码行数:29,代码来源:splitSong.py


示例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)
开发者ID:nithin-vijayan,项目名称:Audio-Surveillance,代码行数:27,代码来源:ui.py


示例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()
开发者ID:agadish,项目名称:HotC,代码行数:32,代码来源:wav_utils.py


示例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()
开发者ID:vish1562,项目名称:TDMA-Music-Streaming,代码行数:33,代码来源:server.py


示例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
开发者ID:assen-totin,项目名称:xbmc-plugin-mmdg,代码行数:34,代码来源:default.py


示例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()
	
开发者ID:a8568730,项目名称:NativeDB,代码行数:31,代码来源:照位置切割音檔.py


示例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
开发者ID:tangentmonger,项目名称:k9markivbm,代码行数:32,代码来源:mod_wum.py


示例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)
开发者ID:crazym,项目名称:SecurityCourse,代码行数:31,代码来源:rc4.py


示例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()
开发者ID:makapuf,项目名称:2313goose,代码行数:27,代码来源:flasher.py


示例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)
开发者ID:dramsay9,项目名称:mindsproutBackend,代码行数:33,代码来源:speechHelperFunctions.py


示例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
开发者ID:dragonfly-science,项目名称:numpy-wavy,代码行数:25,代码来源:wavy.py


示例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")
开发者ID:msallese31,项目名称:chrome-extension-MBN,代码行数:28,代码来源:views.py


示例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
开发者ID:vivek425ster,项目名称:WaveMixer,代码行数:32,代码来源:201202182.py


示例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()
开发者ID:uchicago-bio,项目名称:final-project-manglano,代码行数:32,代码来源:pysynth.py


示例16: slice_wav

def slice_wav(in_file, out_file, start_time, stop_time):
    # Open file
    spf = wave.open(in_file, 'r')
    waveform = spf.readframes(-1)

    # Adjust for stereo vs. mono encoding
    cpf = len(waveform) / spf.getnframes()
    adjusted_sample_rate = spf.getframerate() * cpf

    start_index = adjusted_sample_rate * start_time
    stop_index = adjusted_sample_rate * stop_time

    truncated_wave = waveform[start_index:stop_index]

    # Create and to new file, preserving most params
    f = open(out_file,'a')
    f.close()

    spf2 = wave.open(out_file,'w')

    spf2.setparams(spf.getparams())
    spf2.setnframes(len(truncated_wave) / adjusted_sample_rate)
    spf2.writeframes(truncated_wave)

    spf.close()
    spf2.close()
开发者ID:a2lin,项目名称:secret-octo-wookie,代码行数:26,代码来源:audio_io.py


示例17: trs

        def trs():

            card = 'default'

            opts, args = getopt.getopt(sys.argv[1:], 'c:')
            for o, a in opts:
                if o == '-c':
                    card = a
            n1=e1.get()
            n2=e2.get()
            n3=e3.get()
            n4=e3.get()
            f = wave.open(n1, 'rb')
            A = wave.open(n2, 'rb')
            p = wave.open(n3, 'rb')
            x = wave.open(n4, 'rb')
            sumar(f, A, p,x)



            Archivo5 = Reproducir('sumaa.wav')
            Archivo5.ruta = "sumaa.wav"
            Argumentos = Archivo5.abrir()
            Archivo5.inicio(Argumentos[0],Argumentos[1],Argumentos[2])


            Archivo5.rep()
开发者ID:alejolp96,项目名称:parcial,代码行数:27,代码来源:MainReproducciones.py


示例18: recognize

def recognize(data):
    s = StringIO.StringIO(data)
    s.seek(0)
    r = wave.open(s, "rb")
    frames = r.readframes(11026)
    result = []
    while frames != '':
        md5 = hashlib.md5(frames).hexdigest()
        o = StringIO.StringIO()
        w = wave.open(o, "wb")
        w.setnchannels(r.getnchannels())
        w.setsampwidth(r.getsampwidth())
        w.setframerate(r.getframerate())
        w.writeframes(frames)
        w.close()
        o.seek(0)
        md5 = hashlib.md5(o.read()).hexdigest()
        if md5 in AUDIO_MAP:
            result.append(AUDIO_MAP[md5])
        else:
            (fd, fname) = tempfile.mkstemp(prefix=md5 + "-",
                                           suffix=".wav")
            f = os.fdopen(fd, "wb")
            o.seek(0)
            f.write(o.read())
            f.close()
            log.warning("Unknown individual character, please add %s" % (
                    (fname,)))
            return None
        frames = r.readframes(11026)
    return "".join(result)
开发者ID:electusmatari,项目名称:legacy,代码行数:31,代码来源:griefwatch.py


示例19: save_file

    def save_file(frames):
        p = pyaudio.PyAudio()  # Create a PyAudio session
        if not os.path.isfile(
                WAVE_OUTPUT_FILENAME):  # If there is not such a file
            wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')  # Create the file
            wf.setnchannels(CHANNELS)  # Set number of channels
            wf.setsampwidth(p.get_sample_size(FORMAT))  # Set sampling format
            wf.setframerate(RATE)  # Set Bit Rate / Frame Rate
            wf.writeframes("")  # Write nothing
            wf.close()  # Close the session

        wf = wave.open(WAVE_OUTPUT_FILENAME,
                       'rb')  # Open the file with only read permission
        n_frames = wf.getnframes()  # Get all frames in it
        previous_wav = wf.readframes(
            n_frames)  # Assign all frames to a variable
        wf.close()  # Close the session

        wf = wave.open(WAVE_OUTPUT_FILENAME,
                       'wb')  # Open the file with write permission
        wf.setnchannels(CHANNELS)  # Set number of channels
        wf.setsampwidth(p.get_sample_size(FORMAT))  # Set sampling format
        wf.setframerate(RATE)  # Set Bit Rate / Frame Rate
        wf.writeframes(
            previous_wav +
            b''.join(frames))  # Write the all frames including previous ones
        wf.close()  # Close the session
开发者ID:igorstarki,项目名称:Dragonfire,代码行数:27,代码来源:experimental.py


示例20: audioFromDrama

    def audioFromDrama(dramaName):
        # Go to dir containing audio from subs
        for path, subdirs, files in os.walk(subAudioDir):
            for filename in files:
                if filename == str(dramaName + '.wav'):
                    dramaAudioFileName = os.path.join(
                        path, filename)

        with contextlib.closing(wave.open(
                dramaAudioFileName, 'r')) as dramaAudioFile:
            # Get wave information from drama wave
            rate = dramaAudioFile.getframerate()
            channels = dramaAudioFile.getnchannels()
            sampleWidth = dramaAudioFile.getsampwidth()

            # Make dirs for saving word audio to
            wordDir = os.path.join(subIndvAudioDir, word)

            if not os.path.exists(wordDir):
                os.makedirs(wordDir)

            # Prepare a container for wave data
            dataContainer = []

            # Loop over each instance where the word appears in the drama
            for i in range(0, len(db[word][key])):
                # Set up new file for writing
                # The [i][0] section writes the index number
                # taken from the SRT file.
                # This will allow future lookup of the sentence
                # by index number
                fileName = (word + '_' + dramaName + '_' + str(
                    db[word][key][i][0]) + '.wav')
                filePath = os.path.join(wordDir, fileName)
                extractAudio = wave.open(filePath, 'w')
                extractAudio.setsampwidth(sampleWidth)
                extractAudio.setframerate(rate)
                extractAudio.setnchannels(channels)

                # Set starting point by converting second data from dict
                # to frame position for wave
                dramaAudioFile.setpos(round((db[word][key][i][1]) * rate))
                # Do the same conversion to set the duration of the clip
                # add an extra second on just in case
                # Note: this could result in an error if the final word
                # occurs at the end of a clip. But, with dramas this
                # doesn't happen because of music/credits at the end.
                second = 1 * rate
                duration = round(db[word][key][i][2] * rate + second)
                # Collect data from drama audio file
                for indvFrames in range(0, duration):
                    frame = dramaAudioFile.readframes(1)
                    dataContainer.append(frame)
                # Write data to new word audio file
                for data in range(0, len(dataContainer)):
                    extractAudio.writeframesraw(dataContainer[data])

                extractAudio.close()
                print('Wrote audio file ', fileName)
                dataContainer = []
开发者ID:PrettyCities,项目名称:findclip,代码行数:60,代码来源:subs_extractor.py



注:本文中的wave.open函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python wave.open_audio函数代码示例发布时间:2022-05-26
下一篇:
Python search.search函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap