当前位置:   article > 正文

vue+canvas音频可视化

vue+canvas音频可视化

1.代码 

  1. <template>
  2. <div class="subGuide">
  3. <canvas id="canvas"></canvas>
  4. <br>
  5. <audio id="audio" src="./audio.mp3" controls></audio>
  6. </div>
  7. </template>
  8. <script>
  9. export default {
  10. name: 'subGuide',
  11. data() {
  12. return {
  13. }
  14. },
  15. mounted() {
  16. const audioEle = document.querySelector('audio')
  17. const cvs = document.querySelector('canvas')
  18. const ctx = cvs.getContext('2d')
  19. function initCvs() {
  20. cvs.width = (window.innerWidth / 2) * devicePixelRatio
  21. cvs.height = (window.innerHeight / 3) * devicePixelRatio
  22. }
  23. initCvs()
  24. let isInit = false
  25. let dateArray = null
  26. let analyser = null
  27. audioEle.addEventListener('play', function (e) {
  28. if (isInit) return
  29. const audCtx = new AudioContext()
  30. const source = audCtx.createMediaElementSource(audioEle)
  31. analyser = audCtx.createAnalyser()
  32. analyser.fftSize = 512
  33. dateArray = new Uint8Array(256)
  34. source.connect(analyser)
  35. analyser.connect(audCtx.destination)
  36. isInit = true
  37. })
  38. function draw() {
  39. requestAnimationFrame(draw)
  40. const { width, height } = cvs
  41. ctx.clearRect(0, 0, width, height)
  42. if (!isInit) return
  43. analyser.getByteFrequencyData(dateArray)
  44. const len = dateArray.length / 2.5
  45. ctx.fillStyle = '#266fff'
  46. const barWidth = width / len / 2
  47. for (let i = 0; i < len; i++) {
  48. const data = dateArray[i]
  49. const barHeight = (data / 255) * height
  50. const x1 = i * barWidth + width / 2
  51. const x2 = width / 2 - (i + 1) * barWidth
  52. const y = height - barHeight
  53. ctx.fillRect(x1, y, barWidth - 2, barHeight)
  54. ctx.fillRect(x2, y, barWidth - 2, barHeight)
  55. }
  56. }
  57. draw()
  58. },
  59. methods: {
  60. }
  61. }
  62. </script>
  63. <style lang="scss" scoped></style>

2.效果

音频可视化

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/901733
推荐阅读
相关标签
  

闽ICP备14008679号