Is there anyway to visualize youtube audio from an iframe using the web audio api?

后端 未结 1 1595
无人共我
无人共我 2021-02-04 16:10

Is it possible to listen to the audio of a youtube video that is in an iframe and then analyse it for use in a web audio api based visualizer?

From the way my site is ma

相关标签:
1条回答
  • 2021-02-04 17:07

    Hope this helps any future Googlers.

    The only way I've found to do this is to use an audio streaming lib (like youtube-audio-stream for Node) and buffer/pipe the audio from server-side.

    var express = require('express');
    var router = express.Router();
    
    var youtubeStream = require('youtube-audio-stream');
    
    router.get('/stream/:videoId', function (req, res) {
        try {
            youtubeStream(req.params.videoId).pipe(res);
        } catch (exception) {
            res.status(500).send(exception)
        }
    });
    

    Then you can create audioContext off of it. AudioContext is the magic keyword that you need for visualization with either WebGL or canvas (e.g. pixi.js).

    So on the front-end:

    function loadSound() {
      var request = new XMLHttpRequest();
      request.open("GET", "http://localhost:8000/stream/nl6OW07A5q4", true); 
      request.responseType = "arraybuffer"; 
    
      request.onload = function() {
          var Data = request.response;
          process(Data);
      };
    
      request.send();
    }
    
    function process(Data) {
      source = context.createBufferSource(); // Create Sound Source
      context.decodeAudioData(Data, function(buffer){
        source.buffer = buffer;
        source.connect(context.destination); 
        source.start(context.currentTime);
    }) 
    

    From there on out it should be easy to apply any of the multiple audio visualization libraries out there to the context.

    Basic front-end example from http://www.willvillanueva.com/the-web-audio-api-from-nodeexpress-to-your-browser/

    Edit: archived link https://web.archive.org/web/20170715041035/http://www.willvillanueva.com/the-web-audio-api-from-nodeexpress-to-your-browser/

    0 讨论(0)
提交回复
热议问题