可以使用Web Audio API和createMediaElementSource分析来自Icecast的流式音频吗?

Geo*_*rby 6 javascript audio html5 ios html5-audio

使用Web Audio API和createMediaElement方法,您可以使用类型化数组从<audio>元素中的音频回放中获取频率数据,只要源URL是本地(不是流式传输),它就可以在大多数浏览器中使用.见Codepen:http://codepen.io/soulwire/pen/Dscga

实际代码:

var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var audioElement = new Audio('http://crossorigin.me/http://87.230.103.9:80/top100station.mp3'); // example stream

audioElement.crossOrigin = 'anonymous';
audioElement.type = 'audio/mpeg';

var analyser = audioCtx.createAnalyser();

audioElement.addEventListener('canplay', function() {
  var audioSrc = audioCtx.createMediaElementSource(audioElement);
  // Bind our analyser to the media element source.
  audioSrc.connect(analyser);
  audioSrc.connect(audioCtx.destination);
});

var frequencyData = new Uint8Array(20);

var svgHeight = ($window.innerHeight / 2) - 20;
var svgWidth = $window.innerWidth - 20;
var barPadding = '2';

function createSvg(parent, height, width) {
  return d3.select(parent).append('svg').attr('height', height).attr('width', width);
}

var svg = createSvg('.visualizer', svgHeight, svgWidth);

// Create our initial D3 chart.
svg.selectAll('rect')
   .data(frequencyData)
   .enter()
   .append('rect')
   .attr('x', function (d, i) {
      return i * (svgWidth / frequencyData.length);
   })
   .attr('width', svgWidth / frequencyData.length - barPadding);

// Continuously loop and update chart with frequency data.
function renderChart() {
   requestAnimationFrame(renderChart);

   // Copy frequency data to frequencyData array.
   analyser.getByteFrequencyData(frequencyData);

   console.log(frequencyData);

   // Update d3 chart with new data.
   svg.selectAll('rect')
      .data(frequencyData)
      .attr('y', function(d) {
         return svgHeight - d;
      })
      .attr('height', function(d) {
        return d;
      })
      .style('opacity', function(d) {
        return d / 255;
      })
      .attr('fill', function() {
         return 'rgb(255, 255, 255)';
      });
}

// Run the loop
renderChart();
Run Code Online (Sandbox Code Playgroud)

哪里.visualizer是空的<div>

我正在使用Ionic/Angular开发一个用于广播电台的混合应用程序,而音频流是通过Icecast(http://dir.xiph.org/)进行的,我遇到了以下问题:本地mp3被分析和可视化没问题但是如果你使用流媒体网址,analyser.getByteFrequencyData在iOS Safari中都是零,但它可以正常播放.

所以回顾一下:

兼容性表

我知道在早期版本的Safari中有一个错误,其中createMediaElementSource()会失败,但如果仍然如此,那么它将无法在本地文件上运行?

有任何想法吗?

use*_*476 2

它只是没有按照 Safari 中的规范实现,并且将返回一个零数组而不是流的频率。许多人都观察到了这种行为,例如http://isflashdeadyet.com/tests/web-audio-visualization/index-analysisr.htmlhttps://github.com/Okazari/Rythm.js/issues/7

它应该根据https://browsersupport.io/AnalyserNode.prototype.getByteFrequencyData工作

在这里,您会发现“当在 AnalyserNode 上请求字节数据时,Safari 似乎全面报告没有信号(值为 128)”: http://fourthof5.com/audio-visualization-with-the-web-音频API

在此处测试演示以查看当前状态:http://fourthof5.com/assets/posts/audio-visualization-with-the-web-audio-api/index.html