Reads a .wav file.

    Takes the path, and returns (PCM audio data, sample rate).
180914
def read_wave(path):
    
    with contextlib.closing(wave.open(path, 'rb')) as wf:
        num_channels = wf.getnchannels()
        assert num_channels == 1
        sample_width = wf.getsampwidth()
        assert sample_width == 2
        sample_rate = wf.getframerate()
        assert sample_rate in (8000, 16000, 32000)
        frames = wf.getnframes()
        pcm_data = wf.readframes(frames)
        duration = frames / sample_rate
        return pcm_data, sample_rate, duration
785618
def buffer_to_audio(buffer: bytes) -> np.ndarray:
    """"""
    return np.fromstring(buffer, dtype='<i2').astype(np.float32, order='C') / 32768.0
887148
def play(self, filename, translate=False):  # pragma: no cover
        '''
        
        '''
        # FIXME: Use platform-independent and async audio-output here
        # PyAudio looks most promising, too bad about:
        #  --allow-external PyAudio --allow-unverified PyAudio
        if translate:
            with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
                fname = f.name
            with audioread.audio_open(filename) as f:
                with contextlib.closing(wave.open(fname, 'w')) as of:
                    of.setnchannels(f.channels)
                    of.setframerate(f.samplerate)
                    of.setsampwidth(2)
                    for buf in f:
                        of.writeframes(buf)
            filename = fname

        if winsound:
            winsound.PlaySound(str(filename), winsound.SND_FILENAME)
        else:
            cmd = ['aplay', str(filename)]
            self._logger.debug('Executing %s', ' '.join([pipes.quote(arg) for arg in cmd]))
            subprocess.call(cmd)

        if translate:
            os.remove(fname)
1299085
def load(self, path):
        
        (folder, filename) = os.path.split(path)
        (name, extension) = os.path.splitext(filename)
        return Sound(name, Waveform.load(path))
1041374
def audio_load_time(self):
        
        load_times = self.get_load_times('audio')
        return round(mean(load_times), self.decimal_precision)
592044
def get_sampling_rate(filename):
        '''  '''
        infos = ffmpeg_parse_infos(filename)
        fps = infos.get('audio_fps', 44100)
        if fps == 'unknown':
            fps = 44100
        return fps
230378
def read(filename: str, limit: Optional[int]=None) -> Tuple[list, int]:
    

    audiofile = AudioSegment.from_file(filename)

    if limit:
        audiofile = audiofile[:limit * 1000]

    data = np.fromstring(audiofile._data, np.int16)

    channels = []
    for chn in range(audiofile.channels):
        channels.append(data[chn::audiofile.channels])

    fs = audiofile.frame_rate

    return channels, fs
697789
def read(filename):
    """"""
    return codecs.open(os.path.join(__DIR__, filename), 'r').read()
195058
def num_samples(self):
        
        with audioread.audio_open(self.path) as f:
            return int(f.duration * f.samplerate)
423079
def data_folders(path):
        
        for item in os.listdir(path):
            dir_path = os.path.join(path, item)
            wav_folder = os.path.join(dir_path, 'wav')

            if os.path.isdir(dir_path) and os.path.isdir(wav_folder):
                yield dir_path
312187
def is_wav(origin, filepath, fileobj, *args, **kwargs):
    
    # pylint: disable=unused-argument
    if origin == 'read' and fileobj is not None:
        loc = fileobj.tell()
        fileobj.seek(0)
        try:
            riff, _, fmt = struct.unpack('<4sI4s', fileobj.read(12))
            if isinstance(riff, bytes):
                riff = riff.decode('utf-8')
                fmt = fmt.decode('utf-8')
            return riff == WAV_SIGNATURE[0] and fmt == WAV_SIGNATURE[1]
        except (UnicodeDecodeError, struct.error):
            return False
        finally:
            fileobj.seek(loc)
    elif filepath is not None:
        return filepath.endswith(('.wav', '.wave'))
    else:
        try:
            wave.open(args[0])
        except (wave.Error, AttributeError):
            return False
        else:
            return True
127070
def preview_wave(message, wpm=WPM, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE, word_ref=WORD):
    
    samp_nb = samples_nb(message=message, wpm=wpm, framerate=framerate, word_spaced=False)
    import sounddevice as sd
    lst_bin = _encode_binary(message)
    amplitude = _limit_value(amplitude)
    seconds_per_dot = _seconds_per_dot(word_ref)  # 1.2
    a = [calculate_wave(i, lst_bin, wpm, frequency, framerate, amplitude, seconds_per_dot)
         for i in range(samp_nb)]
    sd.play(a, framerate, blocking=True)
1041297
def _openResources(self):
        
        try:
            rate, data = scipy.io.wavfile.read(self._fileName, mmap=True)
        except Exception as ex:
            logger.warning(ex)
            logger.warning("Unable to read wav with memmory mapping. Trying without now.")
            rate, data = scipy.io.wavfile.read(self._fileName, mmap=False)

        self._array = data
        self.attributes['rate'] = rate
114698
function samples (samplesPath, obj) {
  var files = fs.readdirSync(samplesPath).reduce(function (d, name) {
    var ext = audioExt(name)
    if (ext) d[name.substring(0, name.length - ext.length)] = name
    return d
  }, {})
  var names = Object.keys(files)
  var prefix = sharedStart(names)
  var len = prefix.length
  var samples = names.reduce(function (s, name) {
    s[name.substring(len)] = encode(path.join(samplesPath, files[name]))
    return s
  }, {})
  return obj ? samples : JSON.stringify(samples, null, 2)
}
690758
def data_from_file(file):
    """"""
    fp = wave.open(file, 'r')
    data = fp.readframes(fp.getnframes())
    channels = fp.getnchannels()
    freq = fp.getframerate()
    bits = fp.getsampwidth()

    # Unpack bytes -- warning currently only tested with 16 bit wavefiles. 32
    # bit not supported.
    data = struct.unpack(('%sh' % fp.getnframes()) * channels, data)

    # Only use first channel
    channel1 = []
    n = 0
    for d in data:
        if n % channels == 0:
            channel1.append(d)
        n += 1
    fp.close()
    return (channel1, freq, bits)
292472
private static ByteBuffer convertAudioBytes(AudioFormat format, byte[] audio_bytes, boolean two_bytes_data) {
		ByteBuffer dest = ByteBuffer.allocateDirect(audio_bytes.length);
		dest.order(ByteOrder.nativeOrder());
		ByteBuffer src = ByteBuffer.wrap(audio_bytes);
		src.order(ByteOrder.BIG_ENDIAN);
		if (two_bytes_data) {
			ShortBuffer dest_short = dest.asShortBuffer();
			ShortBuffer src_short = src.asShortBuffer();
			while (src_short.hasRemaining())
				dest_short.put(src_short.get());
		} else {
			while (src.hasRemaining()) {
				byte b = src.get();
				if (format.getEncoding() == Encoding.PCM_SIGNED) {
					b = (byte) (b + 127);
				}
				dest.put(b);
			}
		}
		dest.rewind();
		return dest;
	}
1130187
def encode(self, s):
    
    # Make sure that the data is a single channel, 16bit, 16kHz wave.
    # TODO(chorowski): the directory may not be writable, this should fallback
    # to a temp path, and provide instructions for installing sox.
    if s.endswith(".mp3"):
      # TODO(dliebling) On Linux, check if libsox-fmt-mp3 is installed.
      out_filepath = s[:-4] + ".wav"
      call([
          "sox", "--guard", s, "-r", "16k", "-b", "16", "-c", "1", out_filepath
      ])
      s = out_filepath
    elif not s.endswith(".wav"):
      out_filepath = s + ".wav"
      if not os.path.exists(out_filepath):
        call(["sox", "-r", "16k", "-b", "16", "-c", "1", s, out_filepath])
      s = out_filepath
    rate, data = wavfile.read(s)
    assert rate == self._sample_rate
    assert len(data.shape) == 1
    if data.dtype not in [np.float32, np.float64]:
      data = data.astype(np.float32) / np.iinfo(data.dtype).max
    return data.tolist()