使用Javascript将音频文件添加到AmCharts

时间:2016-10-28 02:34:18

标签: javascript audio amcharts

我使用Amchart的实时编辑器创建了一个图表(x-y图表),我想在图表中添加声音文件(如声音播放器)。图表表示声音文件,因此“播放器”时间位置将对应于图表中x轴上的位置。我希望这些在视觉上匹配,并且可点击的字段可以改变声音文件中的时间以扩展到图表中(就像声音文件正在播放而你想要回到20秒,你会点击左边的玩家,图上的x = 20)

Amcharts允许使用JavaScript进行自定义,因此这是我认为最好将声音文件与其集成的语言。如果视频可以以相同的方式集成,就像在后台播放的视频一样,那也很酷,但不需要添加。

1 个答案:

答案 0 :(得分:0)

如果您的类别/ x轴存储为毫秒,则可以利用音频(或视频)标记的timeupdate事件,并使用图表的showCursorAt对象中的chartCursor方法调用新的时间戳。但是,您需要使用序列图来利用showCursorAt方法。

<强> HTML

<div id="chartdiv"></div>
<audio id="chart-audio" src="/path/to/audio/source"  preload="auto" controls>
</audio>

<强>的JavaScript

AmCharts.useUTC = true; //needed for millisecond timestamps
var chart = AmCharts.makeChart("chartdiv", {
  "type": "serial",
  "theme": "light",
  "dataProvider": [{
    "y": <value>,
    "x": 0
  }, {
    "y": <value>,
    "x": 1000
  }, {
    "y": <value>,
    "x": 2000
  }, {
    "y": <value>,
    "x": 3000
  }, 
  // .. continue until you have the full length of the song in milliseconds
  ],
  // other config ..
  "categoryField": "x",
  "categoryAxis": {
    "parseDates": true,
    "boldPeriodBeginning": false,
    "dateFormats": [{
      "period": "fff",
      "format": "JJ:NN:SS"
    }, {
      "period": "ss",
      "format": "JJ:NN:SS"
    }, {
      "period": "mm",
      "format": "JJ:NN::SS"
    }, {
      "period": "hh",
      "format": "JJ:NN:SS"
    }, {
      "period": "DD",
      "format": "MMM DD"
    }, {
      "period": "WW",
      "format": "MMM DD"
    }, {
      "period": "MM",
      "format": "MMM"
    }, {
      "period": "YYYY",
      "format": "YYYY"
    }],
    "equalSpacing": true,
    "minPeriod": "ss"
  },
  "chartCursor": {
    "categoryBalloonDateFormat": "JJ:NN:SS",
  }
});

var audio = document.getElementById('chart-audio');

audio.addEventListener("timeupdate", function(e) {
  chart.chartCursor.showCursorAt(new Date(Math.floor(e.target.currentTime * 1000)));
});

Demo

修改

您也不一定限于毫秒。如果您有办法将媒体标记的currentTime属性映射到图表中的相应类别,您也可以这样做:

var chart = AmCharts.makeChart("chartdiv", {
  "type": "serial",
  "theme": "light",
  "dataProvider": [{
    "y": 1,
    "measure": 1
  }, {
    "y": 2,
    "measure": 2
  }, {
    "y": 3,
    "measure": 3
  }, {
    "y": 4,
    "measure": 4
  } ],
  "graphs": [{
    "balloonText": "[[category]]: [[value]]",
    "bullet": "circle",
    "valueField": "y",
  }],
  "categoryField": "measure",
  "chartCursor": { },
});

var audio = document.getElementById("chart-audio");

audio.addEventListener("timeupdate", function(e) {
  var measure;
  var currentTime = e.target.currentTime;
  if (currentTime <= 8) {
    measure = 1;
  }
  else if (currentTime <= 16) {
    measure = 2;
  }
  else if (currentTime <= 24) {
    measure = 3;
  }
  else {
    measure = 4;
  }

  chart.chartCursor.showCursorAt(measure);
});

Demo