通过听筒播放<audio>元素

时间:2017-11-18 20:28:29

标签: javascript html5 audio

在网页环境中,有没有办法强制音频通过耳机而不是通过扬声器播放,就像默认情况下那样?这是我的代码,它将base64编码的blob播放到扬声器:

<p><audio id="audio" controls></audio></p>
<script>
// me saying "test"
var message = "GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQRChYECGFOAZwH/////////FUmpZpkq17GDD0JATYCGQ2hyb21lV0GGQ2hyb21lFlSua7uuudeBAXPFh/GhUg8i3WGDgQKGhkFfT1BVU2Oik09wdXNIZWFkAQEAAIC7AAAAAADhibWERzuAAJ+BAR9DtnUB/////////+eBAKNCAIEAAID7g7XJf6AyeBucSGTOZqaZNW+nLcjjtATTiYfGr6c+vz9xfPst4HMXiTw6R5A33H1fJEq6etUCAC89D/qCMpsUUS+O6oSrsVu/5MxHQ8EnTMVvawZNTiDsc32riUlLiUlLJFxRKDzqZuSKZuSLipFUlJATZGATYIggbTPQfc/GPXS3pw36yCLXZ8M0cQFST+Seryn5EPrvszaKlM5JPAvYMeFclsJ9jIxPRPt8PvtUjk9CXlFwUG5/+X+APCPdcDisytQey0ZphfXc5qHo7bmLwNrnuGS2w1MwZunb/JfwZ8F8pk2Z6Y6R80GtC+SkZWDhtVc4bGi9jSObxH/UyviVioE5xe2Fl0cIeOMt9/EVC4Ah928baELKYlTj/GSkXiKzN51bbGmIcDMY4RP5v0m+BP3y02lmcI13POzhufJTJ1xRpi4ATpMBunTAt2155UtP0V2KL9m/gvKDJ/r8/BHpOZOXmo/HEFLWh+OQwAmxwQcePGpQSAVrTIzAXU07GQmJO0Of165509Zj7W810zQRBvM6jAyMjzPv5F4jCMLCYrKfVnctADgwxpFu6yWnm50BiDTbu5BwYIqD1fksTLsIvW+v52BhYkxV9dhkzHEIjlks3tR6GDI9ps4wX9Mhxt+vumW2K0Reo2CNHR1h8dl1erftKBzCmVpATNmEo0EvgQA8gPuDX15BGD0GmGwU+Aja1MuONseRJG/t27twfhCQZGPJUAHWZYo1a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aFZl2T/Dm2HyChxpoKYFvyGAlxCQtTa/cNT8tBzj+xS/eg+o69fClpbJ9vyl/fG3PsFJJdYiEGrcfw4cXS8OzMwsf6e4OiEE25Pz92mChUlXuTsjSO9J1+NmTPriH7L4roFMscann5WPoXDMu0/QxwCHeOjQa39yi7Qp/ZtCWZLJZkrBHyXQiKHSheuSQEsxkk37SixFBlZ6aVUYh+h7KnT4T4pYLsOIOZS4VUIgXgy1TCmNgocICa2ffqvmEb6KThbxjQdvl/3RW6O8P6sXfDcSWvKQK4sERhQkbzh0FUXfud5W0Bq6NKYQyw==";

function b64toBlob(b64Data, contentType, sliceSize) {
  contentType = contentType || '';
  sliceSize = sliceSize || 512;

  var byteCharacters = atob(b64Data);
  var byteArrays = [];

  for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    var slice = byteCharacters.slice(offset, offset + sliceSize);

    var byteNumbers = new Array(slice.length);
    for (var i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    var byteArray = new Uint8Array(byteNumbers);

    byteArrays.push(byteArray);
  }

  var blob = new Blob(byteArrays, {type: contentType});
  return blob;
}
var blob = b64toBlob(message, "video/webm");
  var audio = document.getElementById('audio');
  audio.src = URL.createObjectURL(blob);
  audio.play();
</script>

1 个答案:

答案 0 :(得分:1)

您应该能够使用HTMLMediaElement.setSinkId()来实现这一目标。请注意,该功能是实验API的一部分。目前只有少数浏览器(Chrome 49和Opera 36)支持它。

async function setupAudioOutput(audio) {
  const devices = await navigator.mediaDevices.enumerateDevices();
  const audioDevices = devices.filter(device => device.kind === 'audiooutput');
  await audio.setSinkId(audioDevices[0].deviceId);
}

在创建<audio>元素后调用此函数并将其作为参数传递。