Generates buffers containing PCM data for the audio file.
174133
def read_blocks(self, block_size=4096):
        
        while True:
            out = self.mf.read(block_size)
            if not out:
                break
            yield bytes(out)
928011
def read_data(self, block_samples=1024):
        """"""
        old_width = self._file.getsampwidth()

        while True:
            data = self._file.readframes(block_samples)
            if not data:
                break

            # Make sure we have the desired bitdepth and endianness.
            data = audioop.lin2lin(data, old_width, TARGET_WIDTH)
            if self._needs_byteswap and self._file.getcomptype() != 'sowt':
                # Big-endian data. Swap endianness.
                data = byteswap(data)
            yield data
451473
def save_indexed_audio(self, indexed_audio_file_abs_path):
        
        with open(indexed_audio_file_abs_path, "wb") as f:
            pickle.dump(self.get_timestamps(), f, pickle.HIGHEST_PROTOCOL)
1100181
def modulate(data):
	'''
	 
	'''
	seconds_per_sample = 1.0 / audiogen.sampler.FRAME_RATE
	phase, seconds, bits = 0, 0, 0

	# construct generators
	clock = (x / BAUD_RATE for x in itertools.count(1))
	tones = (MARK_HZ if bit else SPACE_HZ for bit in data)

	for boundary, frequency in itertools.izip(clock, tones):
		# frequency of current symbol is determined by how much 
		# we advance the signal's phase in each audio frame
		phase_change_per_sample = TWO_PI / (audiogen.sampler.FRAME_RATE / frequency)

		# produce samples for the current symbol 
		# until we reach the next clock boundary
		while seconds < boundary:
			yield math.sin(phase)

			seconds += seconds_per_sample
			phase += phase_change_per_sample

			if phase > TWO_PI:
				phase -= TWO_PI

		bits += 1
		logger.debug("bits = %d, time = %.7f ms, expected time = %.7f ms, error = %.7f ms, baud rate = %.6f Hz" \
			% (bits, 1000 * seconds, 1000 * bits / BAUD_RATE, 1000 * (seconds - bits / BAUD_RATE), bits / seconds))
228300
def record(self):
        

        while True:
            frames = []
            self.stream.start_stream()
            for i in range(self.num_frames):
                data = self.stream.read(self.config.FRAMES_PER_BUFFER)
                frames.append(data)
            self.output.seek(0)
            w = wave.open(self.output, 'wb')
            w.setnchannels(self.config.CHANNELS)
            w.setsampwidth(self.audio.get_sample_size(self.config.FORMAT))
            w.setframerate(self.config.RATE)
            w.writeframes(b''.join(frames))
            w.close()
            yield
656096
private void readPCM() throws IOException {
        boolean wrote = false;

        while (true) { // we repeat if the bitstream is chained
            if (endOfBitStream) {
                if (!getPageAndPacket()) {
                    break;
                }
                endOfBitStream = false;
            }

            if (!inited) {
                inited = true;
                return;
            }

            float[][][] _pcm = new float[1][][];
            int[] _index = new int[oggInfo.channels];
            // The rest is just a straight decode loop until end of stream
            while (!endOfBitStream) {
                while (!endOfBitStream) {
                    int result = syncState.pageout(page);

                    if (result == 0) {
                        break; // need more data
                    }

                    if (result == -1) { // missing or corrupt data at this page position
                        logger.log(Level.WARNING, "Corrupt or missing data in bitstream; continuing...");
                    } else {
                        streamState.pagein(page); // can safely ignore errors at
                        // this point
                        while (true) {
                            result = streamState.packetout(packet);

                            if (result == 0) {
                                break; // need more data
                            }
                            if (result == -1) { // missing or corrupt data at this page position
                                // no reason to complain; already complained above
                            } else {
                                // we have a packet.  Decode it
                                int samples;
                                if (vorbisBlock.synthesis(packet) == 0) { // test for success!
                                    dspState.synthesis_blockin(vorbisBlock);
                                }

								// **pcm is a multichannel float vector.  In stereo, for
                                // example, pcm[0] is left, and pcm[1] is right.  samples is
                                // the size of each channel.  Convert the float values
                                // (-1.<=range<=1.) to whatever PCM format and write it out
                                while ((samples = dspState.synthesis_pcmout(_pcm,
                                        _index)) > 0) {
                                    float[][] pcm = _pcm[0];
                                    //boolean clipflag = false;
                                    int bout = (samples < convsize ? samples
                                            : convsize);

									// convert floats to 16 bit signed ints (host order) and
                                    // interleave
                                    for (int i = 0; i < oggInfo.channels; i++) {
                                        int ptr = i * 2;
                                        //int ptr=i;
                                        int mono = _index[i];
                                        for (int j = 0; j < bout; j++) {
                                            int val = (int) (pcm[i][mono + j] * 32767.);
                                            // might as well guard against clipping
                                            if (val > 32767) {
                                                val = 32767;
                                            }
                                            if (val < -32768) {
                                                val = -32768;
                                            }
                                            if (val < 0) {
                                                val = val | 0x8000;
                                            }

                                            if (bigEndian) {
                                                convbuffer[ptr] = (byte) (val >>> 8);
                                                convbuffer[ptr + 1] = (byte) (val);
                                            } else {
                                                convbuffer[ptr] = (byte) (val);
                                                convbuffer[ptr + 1] = (byte) (val >>> 8);
                                            }
                                            ptr += 2 * (oggInfo.channels);
                                        }
                                    }

                                    int bytesToWrite = 2 * oggInfo.channels * bout;
                                    if (bytesToWrite >= pcmBuffer.remaining()) {
                                        logger.log(Level.WARNING, "Read block from OGG that was too big to be buffered: {0}", bytesToWrite);
                                    } else {
                                        pcmBuffer.put(convbuffer, 0, bytesToWrite);
                                    }

                                    wrote = true;
                                    dspState.synthesis_read(bout); // tell libvorbis how
                                    // many samples we
                                    // actually consumed
                                }
                            }
                        }
                        if (page.eos() != 0) {
                            endOfBitStream = true;
                        }

                        if ((!endOfBitStream) && (wrote)) {
                            return;
                        }
                    }
                }

                if (!endOfBitStream) {
                    bytes = 0;
                    int index = syncState.buffer(4096);
                    if (index >= 0) {
                        buffer = syncState.data;
                        try {
                            bytes = input.read(buffer, index, 4096);
                        } catch (Exception e) {
                            logger.log(Level.WARNING, "Failure during vorbis decoding", e);
                            endOfStream = true;
                            return;
                        }
                    } else {
                        bytes = 0;
                    }
                    syncState.wrote(bytes);
                    if (bytes == 0) {
                        endOfBitStream = true;
                    }
                }
            }

			// clean up this logical bitstream; before exit we see if we're
            // followed by another [chained]
            streamState.clear();

			// ogg_page and ogg_packet structs always point to storage in
            // libvorbis.  They're never freed or manipulated directly
            vorbisBlock.clear();
            dspState.clear();
            oggInfo.clear(); // must be called last
        }

        // OK, clean up the framer
        syncState.clear();
        endOfStream = true;
    }
410087
def encode(binary_data):
	'''
	
	'''
	framed_data = frame(binary_data)

	# set volume to 1/2, preceed packet with 1/20 s silence to allow for startup glitches
	for sample in itertools.chain(
		audiogen.silence(1.05), 
		multiply(modulate(framed_data), constant(0.5)), 
		audiogen.silence(1.05), 
	):
		yield sample
388507
def save_beat(
        self,
        output_file_name,
        frequencys,
        play_time,
        sample_rate=44100,
        volume=0.01
    ):
        '''
        
        '''
        left_frequency, right_frequency = frequencys
        left_chunk = self.__create_chunk(left_frequency, play_time, sample_rate)
        right_chunk = self.__create_chunk(right_frequency, play_time, sample_rate)
        frame_list = self.read_stream(left_chunk, right_chunk, volume)

        wf = wave.open(output_file_name, 'wb')
        wf.setparams((2, 2, sample_rate, 0, 'NONE', 'not compressed'))
        wf.writeframes(b''.join(frame_list))
        wf.close()
522033
def to_array(self):
        
        array = super(Audio, self).to_array()
        array['file_id'] = u(self.file_id)  # py2: type unicode, py3: type str

        array['duration'] = int(self.duration)  # type int
        if self.performer is not None:
            array['performer'] = u(self.performer)  # py2: type unicode, py3: type str

        if self.title is not None:
            array['title'] = u(self.title)  # py2: type unicode, py3: type str

        if self.mime_type is not None:
            array['mime_type'] = u(self.mime_type)  # py2: type unicode, py3: type str

        if self.file_size is not None:
            array['file_size'] = int(self.file_size)  # type int
        if self.thumb is not None:
            array['thumb'] = self.thumb.to_array()  # type PhotoSize

        return array
1037275
def write(self, buf):
        
        buf = align_buf(buf, self._sample_width)
        buf = normalize_audio_buffer(buf, self.volume_percentage)
        return self._sink.write(buf)
1353835
public static AudioInputStream setupAudioStream (InputStream in)
        throws UnsupportedAudioFileException, IOException
    {
        AudioInputStream stream = AudioSystem.getAudioInputStream(in);
        AudioFormat format = stream.getFormat();
        if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
            stream = AudioSystem.getAudioInputStream(
                new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                                format.getSampleRate(),
                                16,
                                format.getChannels(),
                                format.getChannels() * 2,
                                format.getSampleRate(),
                                false), stream);
        }

        return stream;
    }
24046
def parse_buffer_to_ppm(data):
    

    images = []

    index = 0

    while index < len(data):
        code, size, rgb = tuple(data[index:index + 40].split(b'\n')[0:3])
        size_x, size_y = tuple(size.split(b' '))
        file_size = len(code) + len(size) + len(rgb) + 3 + int(size_x) * int(size_y) * 3
        images.append(Image.open(BytesIO(data[index:index + file_size])))
        index += file_size

    return images
615629
def compose_from_transcript(files, search, searchtype):
    """"""

    final_segments = []

    if searchtype in ['re', 'word', 'franken', 'fragment']:
        if searchtype == 're':
            searchtype = 'sentence'

        segments = audiogrep.search(search, files, mode=searchtype, regex=True)
        for seg in segments:
            seg['file'] = seg['file'].replace('.transcription.txt', '')
            seg['line'] = seg['words']
            final_segments.append(seg)

    elif searchtype in ['hyper', 'pos']:
        for s in audiogrep.convert_timestamps(files):
            for w in s['words']:
                if search_line(w[0], search, searchtype):
                    seg = {
                        'file': s['file'].replace('.transcription.txt',''),
                        'line': w[0],
                        'start': float(w[1]),
                        'end': float(w[2])
                    }
                    final_segments.append(seg)

    return final_segments
784431
function(wav_file_obj) {

    // console.log("~~~~~~~~~ TOP write_wav ~~~~~~~~~");

    // --- iterate across all properties of given audio file object to see things like sample_rate

    // var sampleRate  = 44100;    // defaults to be overridden in below switch statement
    // var bitDepth    = 16;
    // var numChannels = 1;
    // var pcm_format = 16;
    // var audio_format = 1; // raw PCM


    var sample_rate  = 44100;    // defaults to be overridden in below switch statement
    var bit_depth    = 16;
    var num_channels = 1;
    var pcm_format = 16;   // valid values of Chunk size :   16 or 18 or 40
    var audio_format = 1; // raw PCM

    var path = "unknown_filename_must_populate_filename";
    // var data_length = wav_file_obj.buffer.length;
    var data_length = "unknown_filename_must_populate_buffer";




    // show_object_with_buffer(wav_file_obj, "in write_wav");


    // shared_utils.show_object(wav_file_obj, "total",
    //         "in write_wav", 10);



    for (var property in wav_file_obj) {

        // console.log("1111111  write_wav ", property, wav_file_obj[property]);

        if (wav_file_obj.hasOwnProperty(property)) {

            switch (property) {

                case "sample_rate" : {

                    sample_rate = wav_file_obj[property];
                    break;
                }

                case "bit_depth" : {

                    bit_depth = wav_file_obj[property];
                    break;
                }

                case "num_channels" : {

                    num_channels = wav_file_obj[property];
                    break;
                }

                case "filename" : {

                    path = wav_file_obj[property];
                    break;
                }

                case "buffer" : {

                    data_length = wav_file_obj[property].length;
                    break;
                }

                // --- default - catch all if not identifed above

                default :

                console.log("NOTICE - write_wav ignore this ... seeing property NOT on authorized list : ", 
                                property, " value ", wav_file_obj[property]);
                process.exit(8);

                break;
            };
        };
    };

    // console.log("FFFFFFFF sample_rate  ", sample_rate);
    // console.log("FFFFFFFF bit_depth    ", bit_depth);
    // console.log("FFFFFFFF num_channels ", num_channels);
    // console.log("FFFFFFFF data_length ", data_length);
    // console.log("FFFFFFFF filename ", path);


    // ---

    var size_header = 44;   // constant number of bytes in WAV header as per spec

    var RIFF = new Buffer('RIFF');  // each of these constant MUST remain 4 bytes in size
    var WAVE = new Buffer('WAVE');
    var fmt  = new Buffer('fmt ');
    var data = new Buffer('data');

    // ---

    // var path = wav_file_obj.filename;

    // console.log("/////////// about to write wav output file path ", path);
    // console.log("size buffer to write  ", wav_file_obj.buffer.length);  // deal with 1 channel for now

    // console.log(shared_utils.checkEndian()); // stens TODO - confirm we are on little endian else fiddle

    // ---

    // var data_length = wav_file_obj.buffer.length;

    var entire_size_file = data_length + size_header;

    var write_stream = fs.createWriteStream(path);

    // This is here incase any errors occur
    write_stream.on('error', function (err) {

        console.log("ERROR - seeing error in write_stream");
        console.log(err);
        // process.exit(8);
        return;
    });

    // ---


    write_stream.on('finish', function() {

        // console.error('all writes are now complete.');
    });



    // ---

    var header = new Buffer(size_header);
    var offset = 0;

    // write the "RIFF" identifier
    RIFF.copy(header, offset);  //  chunckID 0 offset  4 bytes
    offset += 4;


    var chunckSize = entire_size_file - 8;
    // write the file size minus the identifier and this 32-bit int
    // header['writeUInt32' + this.endianness](entire_size_file - 8, offset);
    header.writeUInt32LE(chunckSize, offset);   //  chunckSize 4 offset 4 bytes
    offset += 4;
    

    // write the "WAVE" identifier
    WAVE.copy(header, offset);                  // format   8 offset 4 bytes
    offset += 4;


    // write the "fmt " sub-chunk identifier
    fmt.copy(header, offset);                   //  subchunk1ID 12 offset 4 bytes
    offset += 4;


    // write the size of the "fmt " chunk
    // XXX: value of 16 is hard-coded for raw PCM format. other formats have
    // different size.
    // header['writeUInt32' + this.endianness](16, offset);
    // var pcm_format = 16;
    header.writeUInt32LE(pcm_format, offset);   //  subchunk1Size 16 offset 4 bytes
    offset += 4;
    // console.log('write pcm_format ', pcm_format, " post incr offset ", offset);
    // valid values of Chunk size :   16 or 18 or 40



    // write the audio format code
    // header['writeUInt16' + this.endianness](this.format, offset);
    // var audio_format = 1; // raw PCM
    header.writeUInt16LE(audio_format, offset);   //  audioFormat  20 offset 2 bytes    
    offset += 2;
    // console.log('write audio_format ', audio_format, " post incr offset ", offset);


    // write the number of channels
    // var num_channels = 1;
    // header['writeUInt16' + this.endianness](this.channels, offset);
    header.writeUInt16LE(num_channels, offset);   //  num_channels  22 offset 2 bytes     
    offset += 2;

    // console.log('write num_channels ', num_channels, " post incr offset ", offset);

    // write the sample rate
    // var sampleRate = 44100;
    // header['writeUInt32' + this.endianness](this.sampleRate, offset);
    header.writeUInt32LE(sample_rate, offset);   //  sampleRate  24 offset 4 bytes     
    offset += 4;
    // console.log('write sample_rate ', sample_rate, " post incr offset ", offset);


    // var bitDepth = 16;
    // write the byte rate
    var byteRate = this.byteRate;
    if (null == byteRate) {

        byteRate = sample_rate * num_channels * bit_depth / 8;

        // console.log("on write byteRate was null so post calculation its ", byteRate);
    }
    // header['writeUInt32' + this.endianness](byteRate, offset);
    header.writeUInt32LE(byteRate, offset);   //  byteRate  28 offset 4 bytes
    offset += 4;
    // console.log("on write ... byteRate ", byteRate);
    // console.log("on write ... sample_rate ", sample_rate);
    // console.log("on write ... num_channels ", num_channels);
    // console.log("on write ... bit_depth ", bit_depth);


    // console.log('write byteRate ', byteRate, " post incr offset ", offset);


    // write the block align
    var blockAlign = this.blockAlign;
    if (null == blockAlign) {
    blockAlign = num_channels * bit_depth / 8;
    }
    // header['writeUInt16' + this.endianness](blockAlign, offset);
    header.writeUInt16LE(blockAlign, offset);   //  blockAlign  32 offset 2 bytes     
    offset += 2;
    // console.log("on write ... blockAlign ", blockAlign);


    // write the bits per sample
    var bitsPerSample = bit_depth;
    // header['writeUInt16' + this.endianness](this.bitDepth, offset);
    header.writeUInt16LE(bitsPerSample, offset);    //  bitsPerSample  34 offset 2 bytes     
    offset += 2;

    // offset += 2;                                    // filler_01  36 offset 2 bytes - just ignore

    // write the "data" sub-chunk ID
    data.copy(header, offset);                      // subchunk2ID  36 offset 4 bytes
    offset += 4;

    // write the remaining length of the rest of the data
    // header['writeUInt32' + this.endianness](dataLength, offset);
    var subchunk2Size = data_length;
    header.writeUInt32LE(data_length, offset);   //  subchunk2Size  40 offset 4 bytes
    offset += 4;

    if (! (44 == offset)) {

        var err_msg = "ERROR - input file header must contain " + size_header + 
                            " bytes it incorrectly contains : " + offset;

        console.log(err_msg);
        // process.exit(4);
        return;
    }

    // console.log("end of write ........... offset ", offset);

    // ---

    write_stream.write(header);

    // ---

    var buffer_to_file = new Buffer( new Int16Array(wav_file_obj.buffer) );


    write_stream.write(buffer_to_file);

    // console.log("wav_file_obj.buffer ", wav_file_obj.buffer.length);

    // console.log("~~~~~~~~~ BOT write_wav ~~~~~~~~~");

}
1032418
def setup(self, bitdepth=16):
        
        fmt = self.get_file_format()
        newfmt = copy.copy(fmt)

        newfmt.mFormatID = AUDIO_ID_PCM
        newfmt.mFormatFlags = \
            PCM_IS_SIGNED_INT | PCM_IS_PACKED
        newfmt.mBitsPerChannel = bitdepth
        newfmt.mBytesPerPacket = \
            (fmt.mChannelsPerFrame * newfmt.mBitsPerChannel // 8)
        newfmt.mFramesPerPacket = 1
        newfmt.mBytesPerFrame = newfmt.mBytesPerPacket
        self.set_client_format(newfmt)
1005042
def read_data(self, blocksize=4096):
        
        frames = ctypes.c_uint(blocksize // self._client_fmt.mBytesPerFrame)
        buf = ctypes.create_string_buffer(blocksize)

        buflist = AudioBufferList()
        buflist.mNumberBuffers = 1
        buflist.mBuffers[0].mNumberChannels = \
            self._client_fmt.mChannelsPerFrame
        buflist.mBuffers[0].mDataByteSize = blocksize
        buflist.mBuffers[0].mData = ctypes.cast(buf, ctypes.c_void_p)

        while True:
            check(_coreaudio.ExtAudioFileRead(
                self._obj, ctypes.byref(frames), ctypes.byref(buflist)
            ))

            assert buflist.mNumberBuffers == 1
            size = buflist.mBuffers[0].mDataByteSize
            if not size:
                break

            data = ctypes.cast(buflist.mBuffers[0].mData,
                               ctypes.POINTER(ctypes.c_char))
            blob = data[:size]
            yield blob
796863
def _ProcessAudio(self, tag, wall_time, step, audio):
    """"""
    event = AudioEvent(wall_time=wall_time,
                       step=step,
                       encoded_audio_string=audio.encoded_audio_string,
                       content_type=audio.content_type,
                       sample_rate=audio.sample_rate,
                       length_frames=audio.length_frames)
    self.audios.AddItem(tag, event)