Create a stack of waveform images from audio data.
        Return path to created image file.
199214
def waveform_stack(mediafiles, xy_size, output=None, label_style=None, 
        center_color=None, outer_color=None, bg_color=None):
    
    img_files = []
    output = output or os.path.abspath(os.path.dirname(os.path.commonprefix(mediafiles)))
    if os.path.isdir(output):
        output = os.path.join(output, "waveforms.jpg")
    cmd = [config.CMD_IM_MONTAGE] + shlex.split(label_style or WAVE_LABEL_STYLE)
    cmd += ["-tile", "1x%d" % len(mediafiles), "-geometry", "%dx%d" % xy_size, "-label", "%t"]

    try:
        tempdir = tempfile.mktemp(__name__)
        os.makedirs(tempdir) 

        for mediafile in sorted(mediafiles):
            img_files.append(waveform_image(mediafile, xy_size, tempdir, center_color, outer_color, bg_color))

        cmd.extend(img_files)
        cmd.append(output)
        subprocess.check_call(cmd, stdout=open(os.devnull, "wb"), stderr=subprocess.STDOUT)
    finally:
        if os.path.isdir(tempdir):
            shutil.rmtree(tempdir, ignore_errors=True)

    return output
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
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()
1332359
def wave_infochunk(path):
    
    with open(path,'rb') as file:
        if file.read(4) != b"RIFF":
            return None
        data_size = file.read(4) # container size
        if file.read(4) != b"WAVE":
            return None
        while True:
            chunkid = file.read(4)
            sizebuf = file.read(4)
            if len(sizebuf) < 4 or len(chunkid) < 4:
                return None
            size    = struct.unpack(b'<L', sizebuf )[0]
            if chunkid[0:3] != b"fmt":
                if size % 2 == 1:
                    seek = size + 1
                else:
                    seek = size
                file.seek(size,1)
            else:
                return bytearray(b"RIFF" + data_size + b"WAVE" + chunkid + sizebuf + file.read(size))
1054072
def main(input_filename, songname, format, counter):
    

    # open the file & convert to wav
    song_data = AudioSegment.from_file(input_filename, format=format)
    song_data = song_data.set_channels(1)  # convert to mono
    wav_tmp = song_data.export(format="wav")  # write to a tmp file buffer
    wav_tmp.seek(0)
    rate, wav_data = wavfile.read(wav_tmp)

    # extract peaks and compute constellation hashes & offsets
    peaks = resound.get_peaks(np.array(wav_data))
    fingerprints = list(resound.hashes(peaks))  # hash, offset pairs

    if not fingerprints:
        raise RuntimeError("No fingerprints detected in source file - check your parameters passed to Resound.")

    # Combine duplicate keys
    for fp, abs_offset in fingerprints:
        counter[fp].append((abs_offset, songname))

    print "    Identified {} keypoints in '{}'.".format(len(counter), songname)

    return counter
428354
def get_audiomack_data(url):
    

    data = {}
    request = requests.get(url)

    mp3_url = request.text.split('class="player-icon download-song" title="Download" href="')[1].split('"')[0]
    artist = request.text.split('<span class="artist">')[1].split('</span>')[0].strip()
    title = request.text.split('<span class="artist">')[1].split('</span>')[1].split('</h1>')[0].strip()
    artwork_url = request.text.split('<a class="lightbox-trigger" href="')[1].split('" data')[0].strip()

    data['mp3_url'] = mp3_url
    data['title'] = title
    data['artist'] = artist
    data['artwork_url'] = artwork_url
    data['year'] = None

    return data
281317
function AudioFeature() {
      var _this;

      var ua = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
      var flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var cssFlagsPrefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'audio';

      _classCallCheck(this, AudioFeature);

      _this = _possibleConstructorReturn(this, _getPrototypeOf(AudioFeature).call(this, ua, flags, cssFlagsPrefix));

      _this._createTestElements();

      _this.context = _this.getContext();
      _this.formats = {
        mp3: _this.getMp3(),
        webm: _this.getWebm(),
        ogg: _this.getOgg(),
        opus: _this.getOpus(),
        wav: _this.getWav(),
        m4a: _this.getM4a()
      };
      return _this;
    }
1037287
def _read_wave(self, 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)
            pcm_data = wf.readframes(wf.getnframes())
            return pcm_data, sample_rate
552709
def _populate_audio_file(self):
        
        self.log(u"Populate audio file...")
        if self.audio_file_path_absolute is not None:
            self.log([u"audio_file_path_absolute is '%s'", self.audio_file_path_absolute])
            self.audio_file = AudioFile(
                file_path=self.audio_file_path_absolute,
                logger=self.logger
            )
            self.audio_file.read_properties()
        else:
            self.log(u"audio_file_path_absolute is None")
        self.log(u"Populate audio file... done")
1270682
def write_wavefile(f, samples, nframes=None, nchannels=2, sampwidth=2, framerate=44100, bufsize=2048):
    ""
    if nframes is None:
        nframes = 0

    w = wave.open(f, 'wb')
    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 = b''.join(b''.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()
1299085
def load(self, path):
        
        (folder, filename) = os.path.split(path)
        (name, extension) = os.path.splitext(filename)
        return Sound(name, Waveform.load(path))
43710
def serialize(self, image):
        
        pic = mutagen.flac.Picture()
        pic.data = image.data
        pic.type = image.type_index
        pic.mime = image.mime_type
        pic.desc = image.desc or u''
        return pic
311316
def to_array(self):
        
        array = super(Voice, 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.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
        return array
1214940
def generate_samples(self):
        """"""
        filenames = glob_all(self.args.random_data_folder, '*.wav')
        shuffle(filenames)
        while True:
            for fn in filenames:
                for x, y in self.vectors_from_fn(fn):
                    yield x, y
982048
def get_metadata(audio_filepaths):
  
  artist, album, has_embedded_album_art = None, None, None
  for audio_filepath in audio_filepaths:
    try:
      mf = mutagen.File(audio_filepath)
    except Exception:
      continue
    if mf is None:
      continue

    # artist
    for key in ("albumartist", "artist",  # ogg
                "TPE1", "TPE2",  # mp3
                "aART", "\xa9ART"):  # mp4
      try:
        val = mf.get(key, None)
      except ValueError:
        val = None
      if val is not None:
        artist = val[-1]
        break

    # album
    for key in ("_album", "album",  # ogg
                "TALB",  # mp3
                "\xa9alb"):  # mp4
      try:
        val = mf.get(key, None)
      except ValueError:
        val = None
      if val is not None:
        album = val[-1]
        break

    if artist and album:
      # album art
      if isinstance(mf, mutagen.ogg.OggFileType):
        has_embedded_album_art = "metadata_block_picture" in mf
      elif isinstance(mf, mutagen.mp3.MP3):
        has_embedded_album_art = any(map(operator.methodcaller("startswith", "APIC:"), mf.keys()))
      elif isinstance(mf, mutagen.mp4.MP4):
        has_embedded_album_art = "covr" in mf

      # stop at the first file that succeeds (for performance)
      break

  return artist, album, has_embedded_album_art
1243074
def frame_generator(frame_duration_ms, audio, sample_rate):
    
    n = int(sample_rate * (frame_duration_ms / 1000.0) * 2)
    offset = 0
    timestamp = 0.0
    duration = (float(n) / sample_rate) / 2.0
    while offset + n < len(audio):
        yield Frame(audio[offset:offset + n], timestamp, duration)
        timestamp += duration
        offset += n
58260
def convert_to_wav(files):
    ''''''
    converted = []
    for f in files:
        new_name = f + '.temp.wav'
        print(new_name)
        if (os.path.exists(f + '.transcription.txt') is False) and (os.path.exists(new_name) is False):
            subprocess.call(['ffmpeg', '-y', '-i', f, '-acodec', 'pcm_s16le', '-ac', '1', '-ar', '16000', new_name])
        converted.append(new_name)
    return converted