Write a sequence of samples as a WAV file
    Currently a 16 bit mono file
352131
def save(params, filename, source):
    '''
    
    '''
    writer = wave.open(filename, 'wb');
    # Set the WAV file parameters, currently default values
    writer.setnchannels(1)
    writer.setsampwidth(2)
    writer.setframerate(params.sample_rate)
    data_out = array.array('h')
    for x in source:
        data_out.append(int(x * 32766))
    writer.writeframes(data_out.tostring())
    writer.close()
340
def generate_wakeword_pieces(self, volume):
        """"""
        while True:
            target = 1 if random() > 0.5 else 0
            it = self.pos_files_it if target else self.neg_files_it
            sample_file = next(it)
            yield self.layer_with(self.normalize_volume_to(load_audio(sample_file), volume), target)
            yield self.layer_with(np.zeros(int(pr.sample_rate * (0.5 + 2.0 * random()))), 0)
179921
def sample_normalize(self, k_samples=1000, overwrite=False):
        
        log = logUtil.getlogger()
        log.info("Calculating mean and std from samples")
        # if k_samples is negative then it goes through total dataset
        if k_samples < 0:
            audio_paths = self.audio_paths

        # using sample
        else:
            k_samples = min(k_samples, len(self.train_audio_paths))
            samples = self.rng.sample(self.train_audio_paths, k_samples)
            audio_paths = samples
        manager = Manager()
        return_dict = manager.dict()
        jobs = []
        for threadIndex in range(cpu_count()):
            proc = Process(target=self.preprocess_sample_normalize, args=(threadIndex, audio_paths, overwrite, return_dict))
            jobs.append(proc)
            proc.start()
        for proc in jobs:
            proc.join()

        feat = np.sum(np.vstack([item['feat'] for item in return_dict.values()]), axis=0)
        count = sum([item['count'] for item in return_dict.values()])
        feat_squared = np.sum(np.vstack([item['feat_squared'] for item in return_dict.values()]), axis=0)

        self.feats_mean = feat / float(count)
        self.feats_std = np.sqrt(feat_squared / float(count) - np.square(self.feats_mean))
        np.savetxt(
            generate_file_path(self.save_dir, self.model_name, 'feats_mean'), self.feats_mean)
        np.savetxt(
            generate_file_path(self.save_dir, self.model_name, 'feats_std'), self.feats_std)
        log.info("End calculating mean and std from samples")
532110
def main(record_time, audio_sample_rate, audio_sample_width,
         audio_iter_size, audio_block_size, audio_flush_size):
    
    end_time = time.time() + record_time
    audio_device = SoundDeviceStream(sample_rate=audio_sample_rate,
                                     sample_width=audio_sample_width,
                                     block_size=audio_block_size,
                                     flush_size=audio_flush_size)
    stream = ConversationStream(source=audio_device,
                                sink=audio_device,
                                iter_size=audio_iter_size,
                                sample_width=audio_sample_width)
    samples = []
    logging.basicConfig(level=logging.INFO)
    logging.info('Starting audio test.')

    stream.start_recording()
    logging.info('Recording samples.')
    while time.time() < end_time:
        samples.append(stream.read(audio_block_size))
    logging.info('Finished recording.')
    stream.stop_recording()

    stream.start_playback()
    logging.info('Playing back samples.')
    while len(samples):
        stream.write(samples.pop(0))
    logging.info('Finished playback.')
    stream.stop_playback()

    logging.info('audio test completed.')
    stream.close()
1325201
def encode_mp2_from_wav(original_path, mp2_path, options={})
      check_local_file(original_path)

      options.to_options!
      # parse the wave to see what values to use if not overridden by the options
      wf = WaveFile.parse(original_path)
      fmt = wf.chunks[:fmt]

      wav_sample_size = fmt.sample_bits

      # twolame can only handle up to 16 for floating point (seems to convert to 16 internaly anyway)
      # "Note: the 32-bit samples are currently scaled down to 16-bit samples internally."
      # libtwolame.h  twolame_encode_buffer_float32 http://www.twolame.org/doc/twolame_8h.html#8e77eb0f22479f8ec1bd4f1b042f9cd9
      if (fmt.compression_code.to_i == PCM_FLOATING_COMPRESSION && fmt.sample_bits > 32)
        wav_sample_size = 16
      end

      # input options
      prefix_command = ''
      raw_input      = ''
      sample_rate    = "--samplerate #{fmt.sample_rate}"
      sample_bits    = "--samplesize #{wav_sample_size}"
      channels       = "--channels #{fmt.number_of_channels}"
      input_path     = "'#{original_path}'"

      # output options
      mp2_sample_rate = if MP2_SAMPLE_RATES.include?(options[:sample_rate].to_s)
        options[:sample_rate]
      elsif MP2_SAMPLE_RATES.include?(fmt.sample_rate.to_s)
        fmt.sample_rate.to_s
      else
        '44100'
      end

      if mp2_sample_rate.to_i != fmt.sample_rate.to_i
        prefix_command = "#{bin(:sox)} '#{original_path}' -t raw -r #{mp2_sample_rate} - | "
        input_path = '-'
        raw_input = '--raw-input'
      end

      mode = if TWOLAME_MODES.include?(options[:channel_mode])
        options[:channel_mode] #use the channel mode from the options if specified
      elsif fmt.number_of_channels <= 1
        'm' # default to monoaural for 1 channel input
      else
        's' # default to joint stereo for 2 channel input
      end
      channel_mode = "--mode #{mode}"

      kbps = if options[:per_channel_bit_rate]
        options[:per_channel_bit_rate].to_i * ((mode == 'm') ? 1 : 2)
      elsif options[:bit_rate]
        options[:bit_rate].to_i
      else
        0
      end

      kbps = if MP2_BITRATES.include?(kbps)
        kbps
      elsif mode == 'm' || (mode =='a' && fmt.number_of_channels <= 1)
        128 # default for monoaural is 128 kbps
      else
        256 # default for stereo/dual channel is 256 kbps
      end
      bit_rate = "--bitrate #{kbps}"

      downmix = (mode == 'm' && fmt.number_of_channels > 1) ? '--downmix' : ''

      # default these headers when options not present
      protect = (options.key?(:protect) && !options[:protect] ) ? '' : '--protect'
      copyright = (options.key?(:copyright) && !options[:copyright] ) ? '' : '--copyright'
      original = (options.key?(:original) && !options[:original] ) ? '--non-original' : '--original'
      emphasis = (options.key?(:emphasis)) ? "--deemphasis #{options[:emphasis]}" : '--deemphasis n'

      ##
      # execute the command
      ##
      input_options = "#{raw_input} #{sample_rate} #{sample_bits} #{channels}"
      output_options = "#{channel_mode} #{bit_rate} #{downmix} #{protect} #{copyright} #{original} #{emphasis}"

      command = "#{prefix_command} #{bin(:twolame)} -t 0 #{input_options} #{output_options} #{input_path} '#{mp2_path}'"
      out, err = run_command(command)
      unless out.split("\n").last =~ TWOLAME_SUCCESS_RE
        raise "encode_mp2_from_wav - twolame response on transcoding was not recognized as a success, #{out}, #{err}"
      end

      # make sure there is a file at the end of this
      check_local_file(mp2_path)

      true
    end
807503
def write_header(sample_frame_count)
      extensible = @format.channels > 2 ||
                   (@format.sample_format == :pcm && @format.bits_per_sample != 8 && @format.bits_per_sample != 16) ||
                   (@format.channels == 1 && @format.speaker_mapping != [:front_center]) ||
                   (@format.channels == 2 && @format.speaker_mapping != [:front_left, :front_right])
      format_code = extensible ? :extensible : @format.sample_format
      requires_fact_chunk = (format_code != :pcm)

      sample_data_byte_count = sample_frame_count * @format.block_align
      riff_chunk_size = CANONICAL_HEADER_BYTE_LENGTH[format_code] + sample_data_byte_count
      if sample_data_byte_count.odd?
        riff_chunk_size += 1
      end

      # Write the header for the RIFF chunk
      header = CHUNK_IDS[:riff]
      header += [riff_chunk_size].pack(UNSIGNED_INT_32)
      header += WAVEFILE_FORMAT_CODE

      # Write the format chunk
      header += CHUNK_IDS[:format]
      header += [FORMAT_CHUNK_BYTE_LENGTH[format_code]].pack(UNSIGNED_INT_32)
      header += [FORMAT_CODES[format_code]].pack(UNSIGNED_INT_16)
      header += [@format.channels].pack(UNSIGNED_INT_16)
      header += [@format.sample_rate].pack(UNSIGNED_INT_32)
      header += [@format.byte_rate].pack(UNSIGNED_INT_32)
      header += [@format.block_align].pack(UNSIGNED_INT_16)
      header += [@format.bits_per_sample].pack(UNSIGNED_INT_16)
      if format_code == :float
        header += [0].pack(UNSIGNED_INT_16)
      end

      if extensible
        header += [22].pack(UNSIGNED_INT_16)
        header += [@format.bits_per_sample].pack(UNSIGNED_INT_16)
        header += [pack_speaker_mapping(@format.speaker_mapping)].pack(UNSIGNED_INT_32)

        if @format.sample_format == :pcm
          format_guid = WaveFile::SUB_FORMAT_GUID_PCM
        elsif @format.sample_format == :float
          format_guid = WaveFile::SUB_FORMAT_GUID_FLOAT
        end

        header += format_guid
      end

      # Write the FACT chunk, if necessary
      if requires_fact_chunk
        header += CHUNK_IDS[:fact]
        header += [4].pack(UNSIGNED_INT_32)
        header += [sample_frame_count].pack(UNSIGNED_INT_32)
      end

      # Write the header for the data chunk
      header += CHUNK_IDS[:data]
      header += [sample_data_byte_count].pack(UNSIGNED_INT_32)

      @io.write(header)
    end
240532
def writeSampleIndex(self, fp):
        
        print('\n'.join(
            '%d %s' % (index, name) for (index, name) in
            sorted((index, name) for (name, index) in self._samples.items())
        ), file=fp)
1192463
def _preprocess_data(audio_data, verbose=True):
        '''
        
        '''
        from .vggish_input import waveform_to_examples

        last_progress_update = _time.time()
        progress_header_printed = False

        # Can't run as a ".apply(...)" due to numba.jit decorator issue:
        # https://github.com/apple/turicreate/issues/1216
        preprocessed_data, audio_data_index = [], []
        for i, audio_dict in enumerate(audio_data):
            scaled_data = audio_dict['data'] / 32768.0
            data = waveform_to_examples(scaled_data, audio_dict['sample_rate'])

            for j in data:
                preprocessed_data.append([j])
                audio_data_index.append(i)

            # If `verbose` is set, print an progress update about every 20s
            if verbose and _time.time() - last_progress_update >= 20:
                if not progress_header_printed:
                    print("Preprocessing audio data -")
                    progress_header_printed = True
                print("Preprocessed {} of {} examples".format(i, len(audio_data)))
                last_progress_update = _time.time()

        if progress_header_printed:
            print("Preprocessed {} of {} examples\n".format(len(audio_data), len(audio_data)))
        return _np.asarray(preprocessed_data), audio_data_index
634790
def fluid_synth_write_s16_stereo(synth, len):
    
    import numpy
    buf = create_string_buffer(len * 4)
    fluid_synth_write_s16(synth, len, buf, 0, 2, buf, 1, 2)
    return numpy.fromstring(buf[:], dtype=numpy.int16)
781996
def _get_audio_sample_bit(self, audio_abs_path):
        
        sample_bit = int(
           subprocess.check_output(
               ("""sox --i {} | grep "{}" | awk -F " : " '{{print $2}}' | grep -oh "^[^-]*" """).format(audio_abs_path, "Precision"),
               shell=True, universal_newlines=True).rstrip())
        return sample_bit
99730
def write(self, buf):
        """"""
        underflow = self._audio_stream.write(buf)
        if underflow:
            logging.warning('SoundDeviceStream write underflow (size: %d)',
                            len(buf))
        return len(buf)
357096
private static final void splitSamplesToBytes(int[] samples, int totalSamples,
    int bytesPerSample, byte[] dataMD5) {
    int destIndexBase = 0;
    int i = 0;
    
    switch(bytesPerSample) {
      case 3:
        for(; i < totalSamples; i++) {
        dataMD5[destIndexBase++] = (byte)(samples[i]);
        dataMD5[destIndexBase++] = (byte)(samples[i] >> 8);
        dataMD5[destIndexBase++] = (byte)(samples[i] >> 16);
        }
        break;
      case 2:
        for(; i < totalSamples; i++) {
        dataMD5[destIndexBase++] = (byte)(samples[i]);
        dataMD5[destIndexBase++] = (byte)(samples[i] >> 8);
        }
        break;
      case 1:
        for(; i < totalSamples; i++) {
        dataMD5[i] = (byte)samples[i];
        }
    }
  }
785560
def compose(segments, out='out.mp3', padding=0, crossfade=0, layer=False):
    ''''''

    files = {}

    working_segments = []

    audio = AudioSegment.empty()

    if layer:
        total_time = max([s['end'] - s['start'] for s in segments]) * 1000
        audio = AudioSegment.silent(duration=total_time)

    for i, s in enumerate(segments):
        try:
            start = s['start'] * 1000
            end = s['end'] * 1000
            f = s['file'].replace('.transcription.txt', '')
            if f not in files:
                if f.endswith('.wav'):
                    files[f] = AudioSegment.from_wav(f)
                elif f.endswith('.mp3'):
                    files[f] = AudioSegment.from_mp3(f)

            segment = files[f][start:end]

            print(start, end, f)

            if layer:
                audio = audio.overlay(segment, times=1)
            else:
                if i > 0:
                    audio = audio.append(segment, crossfade=crossfade)
                else:
                    audio = audio + segment

            if padding > 0:
                audio = audio + AudioSegment.silent(duration=padding)

            s['duration'] = len(segment)
            working_segments.append(s)
        except:
            continue

    audio.export(out, format=os.path.splitext(out)[1].replace('.', ''))
    return working_segments
891765
def _spectrogram_mono(self, x):
        ''''''
        x = K.permute_dimensions(x, [0, 2, 1])
        x = K.expand_dims(x, 3)  # add a dummy dimension (channel axis)
        subsample = (self.n_hop, 1)
        output_real = K.conv2d(x, self.dft_real_kernels,
                               strides=subsample,
                               padding=self.padding,
                               data_format='channels_last')
        output_imag = K.conv2d(x, self.dft_imag_kernels,
                               strides=subsample,
                               padding=self.padding,
                               data_format='channels_last')
        output = output_real ** 2 + output_imag ** 2
        # now shape is (batch_sample, n_frame, 1, freq)
        if self.image_data_format == 'channels_last':
            output = K.permute_dimensions(output, [0, 3, 1, 2])
        else:
            output = K.permute_dimensions(output, [0, 2, 3, 1])
        return output
924461
public void decodeBytes(byte[] audioBytes, double[] audioSamples) {
        int sampleSizeInBytes = getFormat().getSampleSizeInBits() / 8;
        int[] sampleBytes = new int[sampleSizeInBytes];
        int k = 0; // index in audioBytes
        for (int i = 0; i < audioSamples.length; i++) {
            // collect sample byte in big-endian order
            if (getFormat().isBigEndian()) {
                // bytes start with MSB
                for (int j = 0; j < sampleSizeInBytes; j++) {
                    sampleBytes[j] = audioBytes[k++];
                }
            } else {
                // bytes start with LSB
                for (int j = sampleSizeInBytes - 1; j >= 0; j--) {
                    sampleBytes[j] = audioBytes[k++];
                    if (sampleBytes[j] != 0)
                        j = j + 0;
                }
            }
            // get integer value from bytes
            int ival = 0;
            for (int j = 0; j < sampleSizeInBytes; j++) {
                ival += sampleBytes[j];
                if (j < sampleSizeInBytes - 1)
                    ival <<= 8;
            }
            // decode value
            double ratio = Math.pow(2., getFormat().getSampleSizeInBits() - 1);
            double val = ((double) ival) / ratio;
            audioSamples[i] = val;
        }
    }
894320
def play_beat(
        self,
        frequencys,
        play_time,
        sample_rate=44100,
        volume=0.01
    ):
        '''
        
        '''

        # 依存するライブラリの基底オブジェクト
        audio = pyaudio.PyAudio()
        # ストリーム
        stream = audio.open(
            format=pyaudio.paFloat32,
            channels=2,
            rate=sample_rate,
            output=1
        )
        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)
        self.write_stream(stream, left_chunk, right_chunk, volume)
        stream.stop_stream()
        stream.close()
        audio.terminate()
227931
def convert(self):
        
        wav_directory = self._pre_convert()
        for mp3_filename in self.mp3_directory.glob('**/*.mp3'):
            wav_filename = path.join(wav_directory, os.path.splitext(os.path.basename(mp3_filename))[0] + ".wav")
            if not path.exists(wav_filename):
                _logger.debug("Converting mp3 file %s to wav file %s" % (mp3_filename, wav_filename))
                transformer = Transformer()
                transformer.convert(samplerate=SAMPLE_RATE, n_channels=N_CHANNELS, bitdepth=BITDEPTH)
                transformer.build(str(mp3_filename), str(wav_filename))
            else:
                _logger.debug("Already converted mp3 file %s to wav file %s" % (mp3_filename, wav_filename))
        return wav_directory