determines if the the audiotrack meets minimum standards to be encoded
174106
private function audioCanBeEncoded($resolution, $metainfo) {
         return
             // sample rate of file is better or as good as defined in resolution
             $resolution['audio_sample_rate'] >= $metainfo['sample_rate'] &&
             // bitrate of file is better or as good as defined in resolution
             $resolution['audio_bitrate'] <= $metainfo['max_bit_rate'] ||
             // or we allow worse quality to be used for encoding
             filter_var(
                 $resolution['allow_lower_audio_bitrate'],
                 FILTER_VALIDATE_BOOLEAN
             )
         ;
     }
465031
public static function allow_track() {
        $DoNotTrackHeader = "DNT";
        $DoNotTrackValue = "1";

        $phpHeader = "HTTP_" . strtoupper(str_replace("-", "_", $DoNotTrackHeader));

        $retval = ! ((array_key_exists($phpHeader, $_SERVER)) and ($_SERVER[$phpHeader] == $DoNotTrackValue));
        return $retval;
    }
803451
def from_Track(track):
    """"""
    # Throw exception
    if not hasattr(track, 'bars'):
        return False
    lastkey = Key('C')
    lasttime = (4, 4)

    # Handle the Bars:
    result = ''
    for bar in track.bars:
        if lastkey != bar.key:
            showkey = True
        else:
            showkey = False
        if lasttime != bar.meter:
            showtime = True
        else:
            showtime = False
        result += from_Bar(bar, showkey, showtime) + ' '
        lastkey = bar.key
        lasttime = bar.meter
    return '{ %s}' % result
921668
def is_fulltrack_available(self):
        """"""

        doc = self._request(self.ws_prefix + ".getInfo", True)
        return (
            doc.getElementsByTagName("streamable")[0].getAttribute("fulltrack") == "1"
        )
508119
def tag_audio(filename, tracklisting):
    """"""
    # TODO: maybe actually glob for files, then try tagging if present?
    if not(tag_audio_file(filename + '.m4a', tracklisting) or
           tag_audio_file(filename + '.mp3', tracklisting)):
        print("Cannot find or access any relevant M4A or MP3 audio file.")
        print("Trying to save a text file instead.")
        write_text(filename, tracklisting)
        return False
    return True
81160
def validate_sound(sound,
                   token):
    '''
    
    '''
    ret = {
            'message': 'Sound is invalid',
            'res': False
           }
    parameters = dict()
    parameters['token'] = token

    response = query(function='validate_sound',
                     method='GET',
                     query_params=parameters)

    if response['res']:
        if 'message' in response:
            _message = response.get('message', '')
            if 'status' in _message:
                if _message.get('dict', {}).get('status', '') == 1:
                    sounds = _message.get('dict', {}).get('sounds', '')
                    if sound in sounds:
                        ret['message'] = 'Valid sound {0}.'.format(sound)
                        ret['res'] = True
                    else:
                        ret['message'] = 'Warning: {0} not a valid sound.'.format(sound)
                        ret['res'] = False
                else:
                    ret['message'] = ''.join(_message.get('dict', {}).get('errors'))
    return ret
1369939
function (result) {
            if (result.stat('audioInputLevel')) {
              currentStats.audioSentPackets = Number(result.stat('packetsSent'));
              currentStats.audioSentPacketsLost = Number(result.stat('packetsLost'));
              currentStats.audioSentBytes =  Number(result.stat('bytesSent'));
              currentStats.audioCodec = result.stat('googCodecName');
              currentStats.audioRtt = Number(result.stat('googRtt'));
            } else if (result.stat('audioOutputLevel')) {
              currentStats.audioRecvPackets = Number(result.stat('packetsReceived'));
              currentStats.audioRecvPacketsLost = Number(result.stat('packetsLost'));
              currentStats.audioRecvBytes =  Number(result.stat('bytesReceived'));
              currentStats.audioCodec = result.stat('googCodecName');
            }
          }
547865
public boolean check() throws Exception {
        format = FORMAT_UNSUPPORTED;
        // create a temporary copy from input
        File fileCopy = File.createTempFile("modeshape-sequencer-audio", ".tmp");
        IoUtil.write(in, new BufferedOutputStream(new FileOutputStream(fileCopy)));

        if (mimeType.startsWith("audio/mpeg")) {
            format = FORMAT_MP3;
            audioFile = new MP3FileReader().read(fileCopy);
        } else if (mimeType.startsWith("audio/vorbis") || mimeType.startsWith("audio/x-vorbis") || mimeType.startsWith("audio/ogg")) {
            format = FORMAT_VORBIS;
            audioFile = new OggFileReader().read(fileCopy);
        } else if (mimeType.startsWith("audio/flac") || mimeType.startsWith("audio/x-flac")) {
            format = FORMAT_FLAC;
            audioFile = new FlacFileReader().read(fileCopy);
        } else if (mimeType.equals("audio/mp4") || mimeType.equals("video/mp4") || mimeType.equals("video/quicktime")) {
            format = FORMAT_MP4;
            audioFile = new Mp4FileReader().read(fileCopy);
        } else if (mimeType.equals("audio/x-ms-wma")) {
            format = FORMAT_WMA;
            audioFile = new AsfFileReader().read(fileCopy);
        } else if (mimeType.startsWith("audio/x-wav") || mimeType.startsWith("audio/wav")) {
            format = FORMAT_WAV;
            audioFile = new WavFileReader().read(fileCopy);
        }

        // try to delete the file immediately or on JVM exit
        boolean deleted = false;
        try {
            deleted = fileCopy.delete();
        } catch (SecurityException e) {
            // ignore
        }
        if (!deleted) {
            fileCopy.deleteOnExit();
        }
        return checkSupportedAudio();
    }
546986
boolean validateAudience(List<String> allowedAudiences, List<String> audiences) {
		boolean valid = false;

		if (allowedAudiences != null && allowedAudiences.contains(Constants.ALL_AUDIENCES)) {
			return true;
		}
		if (allowedAudiences != null && audiences != null) {
			for (String audience : audiences) {
				for (String allowedAud : allowedAudiences) {
					if (allowedAud.equals(audience)) {
						valid = true;
						break;
					}
				}
			}
		} else if (allowedAudiences == null && (audiences == null || audiences.isEmpty())) {
			valid = true;
		}

		return valid;
	}
1210125
def scan(audio_filepaths, *, album_gain=False, skip_tagged=False, thread_count=None, ffmpeg_path=None, executor=None):
  
  r128_data = {}

  with contextlib.ExitStack() as cm:
    if executor is None:
      if thread_count is None:
        try:
          thread_count = len(os.sched_getaffinity(0))
        except AttributeError:
          thread_count = os.cpu_count()
      enable_ffmpeg_threading = thread_count > (len(audio_filepaths) + int(album_gain))
      executor = cm.enter_context(concurrent.futures.ThreadPoolExecutor(max_workers=thread_count))
      asynchronous = False
    else:
      enable_ffmpeg_threading = False
      asynchronous = True

    loudness_tags = tuple(map(has_loudness_tag, audio_filepaths))

    # remove invalid files
    audio_filepaths = tuple(audio_filepath for (audio_filepath,
                                                has_tags) in zip(audio_filepaths,
                                                                 loudness_tags) if has_tags is not None)
    loudness_tags = tuple(filter(None, loudness_tags))

    futures = {}
    if album_gain:
      if skip_tagged and all(map(operator.itemgetter(1), loudness_tags)):
        logger().info("All files already have an album gain tag, skipping album gain scan")
      elif audio_filepaths:
        calc_album_peak = any(map(lambda x: os.path.splitext(x)[-1].lower() != ".opus",
                                  audio_filepaths))
        futures[ALBUM_GAIN_KEY] = executor.submit(get_r128_loudness,
                                                  audio_filepaths,
                                                  calc_peak=calc_album_peak,
                                                  enable_ffmpeg_threading=enable_ffmpeg_threading,
                                                  ffmpeg_path=ffmpeg_path)
    for audio_filepath in audio_filepaths:
      if skip_tagged and has_loudness_tag(audio_filepath)[0]:
        logger().info("File '%s' already has a track gain tag, skipping track gain scan" % (audio_filepath))
        continue
      if os.path.splitext(audio_filepath)[-1].lower() == ".opus":
        # http://www.rfcreader.com/#rfc7845_line1060
        calc_peak = False
      else:
        calc_peak = True
      futures[audio_filepath] = executor.submit(get_r128_loudness,
                                                (audio_filepath,),
                                                calc_peak=calc_peak,
                                                enable_ffmpeg_threading=enable_ffmpeg_threading,
                                                ffmpeg_path=ffmpeg_path)

    if asynchronous:
      return futures

    for audio_filepath in audio_filepaths:
      try:
        r128_data[audio_filepath] = futures[audio_filepath].result()
      except KeyError:
        # track gain was skipped
        pass
      except Exception as e:
        # raise
        logger().warning("Failed to analyze file '%s': %s %s" % (audio_filepath,
                                                                 e.__class__.__qualname__,
                                                                 e))
    if album_gain and audio_filepaths:
      try:
        r128_data[ALBUM_GAIN_KEY] = futures[ALBUM_GAIN_KEY].result()
      except KeyError:
        # album gain was skipped
        pass
      except Exception as e:
        # raise
        logger().warning("Failed to analyze files %s: %s %s" % (", ".join("'%s'" % (audio_filepath) for audio_filepath in audio_filepaths),
                                                                e.__class__.__qualname__,
                                                                e))
  return r128_data
524367
function onAudioInputCapture(evt) {
    try {
        if (evt && evt.data) {
            // Increase the debug counter for received data
            totalReceivedData += evt.data.length;

            // Add the chunk to the buffer
            audioDataBuffer = audioDataBuffer.concat(evt.data);
        }
    }
    catch (ex) {
        alert("onAudioInputCapture ex: " + ex);
    }
}
958155
@Override
    public boolean isConversionSupported(
            AudioFormat targetFormat,
            AudioFormat sourceFormat) {
        LOG.log(Level.FINE, ">TFormatConversionProvider.isConversionSupported(AudioFormat, AudioFormat):");
        LOG.log(Level.FINE, "class: {0}", getClass().getName());
        LOG.log(Level.FINE, "checking if conversion possible");
        LOG.log(Level.FINE, "from: {0}", sourceFormat);
        LOG.log(Level.FINE, "to: {0}", targetFormat);
        AudioFormat[] aTargetFormats = getTargetFormats(targetFormat.getEncoding(), sourceFormat);
        for (AudioFormat aTargetFormat : aTargetFormats) {
            LOG.log(Level.FINE, "checking against possible target format: {0}", aTargetFormat);
            if (aTargetFormat != null && AudioFormats.matches(aTargetFormat, targetFormat)) {
                LOG.log(Level.FINE, "<result=true");
                return true;
            }
        }
        LOG.log(Level.FINE, "<result=false");
        return false;
    }
132581
function(input_32_bit_buffer) {

		// this method is LOSSY - intended as preliminary step when saving audio into WAV format files
		//                        output is a byte array where the 16 bit output format 
		//						  is spread across two bytes in little endian ordering

	    var size_source_buffer = input_32_bit_buffer.length;

	    var buffer_byte_array = new Int16Array(size_source_buffer * 2); // Int8Array 8-bit twos complement signed integer

	    var value_16_bit_signed_int;
	    var index_byte = 0;


	    for (var index = 0; index < size_source_buffer; index++) {

	        value_16_bit_signed_int = ~~((0 < input_32_bit_buffer[index]) ? input_32_bit_buffer[index] * 0x7FFF : 
	        																input_32_bit_buffer[index] * 0x8000);

	        buffer_byte_array[index_byte] = value_16_bit_signed_int & 0xFF;

	        var byte_two_of_two = (value_16_bit_signed_int >> 8);

	        buffer_byte_array[index_byte + 1] = byte_two_of_two;

	        index_byte += 2;
	    };

	    // ---

	    return buffer_byte_array;
	}
393132
function encodeTrack(track) {
    var events = track.getEvents(), data = [],
        length = events.length, i,
        runningStatus = null, result;

    for (i = 0; i < length; i += 1) {
        result = encodeEvent(events[i], runningStatus);
        runningStatus = result.runningStatus;

        data[i] = result.data;
    }

    return encodeChunk('MTrk', buffer.Buffer.concat(data));
}
1360308
def real_sound_match_abstract_sound(self, abstract_pos: AbstractPosition) -> bool:
        
        assert isinstance(abstract_pos, AbstractPosition)
        if self.before is not None and self.after is not None:
            return self.position == abstract_pos.position and self.before.match_list(abstract_pos.before) and \
                   self.after.match_list(abstract_pos.after)
        elif self.before is None and self.after is None:
            return self.position == abstract_pos.position
        elif self.before is None:
            return self.position == abstract_pos.position and self.after.match_list(abstract_pos.after)
        else:
            return self.position == abstract_pos.position and self.before.match_list(abstract_pos.before)
637205
function() {
      var self = this || Howler;
      var audioTest = null;

      // Must wrap in a try/catch because IE11 in server mode throws an error.
      try {
        audioTest = (typeof Audio !== 'undefined') ? new Audio() : null;
      } catch (err) {
        return self;
      }

      if (!audioTest || typeof audioTest.canPlayType !== 'function') {
        return self;
      }

      var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, '');

      // Opera version <33 has mixed MP3 support, so we need to check for and block it.
      var checkOpera = self._navigator && self._navigator.userAgent.match(/OPR\/([0-6].)/g);
      var isOldOpera = (checkOpera && parseInt(checkOpera[0].split('/')[1], 10) < 33);

      self._codecs = {
        mp3: !!(!isOldOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))),
        mpeg: !!mpegTest,
        opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''),
        ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
        oga: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
        wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''),
        aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''),
        caf: !!audioTest.canPlayType('audio/x-caf;').replace(/^no$/, ''),
        m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
        mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
        weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''),
        webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''),
        dolby: !!audioTest.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/, ''),
        flac: !!(audioTest.canPlayType('audio/x-flac;') || audioTest.canPlayType('audio/flac;')).replace(/^no$/, '')
      };

      return self;
    }
397551
function () {
      var dnt = navigator.doNotTrack || navigator.msDoNotTrack || window.doNotTrack;
      return (dnt !== null && dnt !== undefined) ? (dnt && dnt !== 'yes' && dnt !== 1 && dnt !== '1') : true;
    }