jaysalvat / buzz

Buzz is a small but powerful Javascript library that allows you to easily take advantage of the new HTML5 audio element. It tries to degrade silently on non-modern browsers.
http://buzz.jaysalvat.com
MIT License
1.21k stars 227 forks source link

Can I access the audio context somehow? #119

Closed domeniko-gentner closed 5 years ago

domeniko-gentner commented 5 years ago

I am looking to create a media analyser with your library and require access to the audio context. Is there some way to get it? I couldn't find anything in the docs and the source is not easy to read for me. Thanks for the help.

Example:

    snd = new buzz.sound(conf_station,{
        formats: ['mp3', 'aac', 'ogg'],
        preload: true,
        autoplay: true,
        loop: false,
        crossOrigin: true,
        webAudioApi: true,
        volume: conf_volume
    });
    audioContext = snd.audioCtx; // This fails, creating a new context returns arrays with zeroes and I don't mean the Mitsubishi A6M
    audioAnalyser = audioContext.createAnalyser();
    audioAnalyser.fttSize = 1024;
    var bufferLength = audioAnalyser.frequencyBinCount;
    var dataArray = new Uint8Array(bufferLength);
    audioAnalyser.getByteTimeDomainData(dataArray);

    snd.load().bind('canplaythrough', function(e){
        radio.play();
    });

    setInterval(function(){
        array = new Uint8Array(audioAnalyser.frequencyBinCount);
        console.log(audioAnalyser.getByteFrequencyData(array));
    }, 1000);
domeniko-gentner commented 5 years ago

Finally found it out myself. Here is the code if anyone runs into a similar issue:

    if (snd== null)
    {
        snd= new buzz.sound(conf_station,{
            formats: ['aac'],
            preload: true,
            autoplay: true,
            loop: false,
            crossOrigin: true,
            webAudioApi: true,
            volume: conf_volume
        });
        audioContext = buzz.audioCtx;
        audioAnalyser = audioContext.createAnalyser();

        audioAnalyser.fttSize = 40;
        bufferLength = audioAnalyser.frequencyBinCount;
        var dataArray = new Uint8Array(bufferLength);
        audioAnalyser.getByteFrequencyData(dataArray);

        snd.load().bind('canplaythrough', function(e){
            this.source.connect(audioAnalyser);
            snd.play();
        })
    }

// different function:
    var array = new Uint8Array(audioAnalyser.frequencyBinCount);
    audioAnalyser.getByteFrequencyData(array);