![]() ![]() open(filename, 'w') w.setparams((nchannels, sampwidth, framerate, nframes, 'NONE', 'not compressed')) max_amplitude = float( int(( 2 ** (sampwidth * 8)) / 2) - 1) # split the samples into chunks (to reduce memory consumption and improve performance) for chunk in grouper(bufsize, samples): frames = ''.join( ''.join(struct.pack( 'h', int(max_amplitude * sample)) for sample in channels) for channels in chunk if channels is not None) w.writeframesraw(frames) w.close() return filename wavebender So, putting all of this together, we end up with something like this:ĭef grouper(n, iterable, fillvalue = None): "grouper(3, 'ABCDEFG', 'x') -> ABC DEF Gxx" args = * n return izip_longest(fillvalue =fillvalue, *args) def write_wavefile(filename, samples, nframes = None, nchannels = 2, sampwidth = 2, framerate = 44100, bufsize = 2048): if nframes is None: nframes = -1 w = wave. This offers the advantages of both techniques. Thus, we take the third approach: buffer chunks of the audio stream and write each chunk as it is computed. Second, it means you can’t stream the audio as it is generated, which means you can’t play the audio in realtime (by writing to stdout and piping to aplay, for example). First, it requires a huge amount of memory, since the entire. This does not incur the aforementioned performance penalty, but it has two major problems. On the other extreme, we pre-compute the entire file and write all of the samples at once. This is memory-efficient, but incurs a severe performance penalty due to the overhead of writing to the file. On one extreme, we write data to the file every time we compute a sample. In other words, the channels are interleaved.įinally, we want to keep performance in mind. Where L1 is the first sample in the left channel, R1 is the first sample in the right channel, and so on. wav files look something like this: L1R1L2R2元R3L4R4 Now, we are going to be creating stereo audio files, so we need to consider how. To open a wavefile for writing with the wave module, do this: This is equal to the framerate multiplied by the duration of the file in seconds.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |