[前端]利用WebAudioAPI獲取音頻頻譜(html5音頻可視化)

項(xiàng)目希望可以把音頻可視化,有條隨聲音波動(dòng)的曲線或者是像唱吧那種。開始是搜到了騰訊大腿(TGideas)寫的audio可視化組件,想著直接用,后來各種原因還是打算自己重新寫一個(gè)……雖然明顯寫得low了很多。
騰訊大腿的audio組件地址
http://www.3fwork.com/b403/001620MYM013253/
GitHub
https://github.com/tgideas/motion/blob/master/component/src/main/audio/audio.js

然后參照了官方api
https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API
還有一篇也是audio可視化的文章
http://www.mizuiren.com/330.html

注意audioContext.currentTime是從audioContext開始創(chuàng)建之后開始計(jì)算的

代碼:

var Visualizer = function(config) {
    this.audioContext = null;
    this.analyser = null;
    this.source = null; //the audio source
    this.config = config;
    this.frequency = [];
    this.playing = false;
    this.ready = false;
    this.loadFailed = false;
};
Visualizer.prototype = {
    init: function () {
        this._prepare();
        this.getData();
        this._analyser();
    },
    _prepare: function () {
        //實(shí)例化一個(gè)音頻上下文類型window.AudioContext。目前Chrome和Firefox對(duì)其提供了支持,但需要相應(yīng)前綴,Chrome中為window.webkitAudioContext,F(xiàn)irefox中為mozAudioContext。
        // 所以為了讓代碼更通用,能夠同時(shí)工作在兩種瀏覽器中,只需要一句代碼將前綴進(jìn)行統(tǒng)一即可。
        window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
        try {
            this.audioContext = new AudioContext();
 
        } catch (e) {
            console.log(e);
        }
    },
    _analyser: function () {
        var that = this;
        that.analyser = that.audioContext.createAnalyser();
        that.analyser.smoothingTimeConstant = 0.85;
        that.analyser.fftSize = 32;//傅里葉變換參數(shù) 簡(jiǎn)化成16個(gè)元素?cái)?shù)組
        //將source與分析器連接
        that.source.connect(that.analyser);
        //將分析器與destination連接,這樣才能形成到達(dá)揚(yáng)聲器的通路
        that.analyser.connect(that.audioContext.destination);
        that.frequency = new Uint8Array(that.analyser.frequencyBinCount);

    },
    getData: function () {
        var that = this;
        //建立緩存源
        that.source = that.audioContext.createBufferSource();
        var request = new XMLHttpRequest();
        //請(qǐng)求資源
        request.open('GET', that.config.url, true);
        request.responseType = 'arraybuffer';
        request.onreadystatechange=function() {
            if (request.readyState === 4) {
                if (request.status === 200) {
                    that.ready = true;
                } else {
                    that.loadFailed = true;
                }
            }
        };
        request.onload = function() {
            var audioData = request.response;
            //解碼
            that.audioContext.decodeAudioData(audioData, function(buffer) {
                        that.source.buffer = buffer;
//                        console.log(buffer.duration);//資源長(zhǎng)度
//                        that.source.connect(that.audioContext.destination);
                        //將audioBufferSouceNode連接到audioContext.destination,
                        // 這個(gè)AudioContext的destination也就相關(guān)于speaker(揚(yáng)聲器)。
                        that.source.loop = that.config.loop||false;

                    },
                    function(e){"Error with decoding audio data" + e.err});
        };
        request.send();
    },
    play: function () {
        var that = this;
        that.source.start(0);
        that.playing = true;
        var timer = setInterval(function () {
            that.analyser.getByteFrequencyData(that.frequency);
            if (that.source.buffer){
                if (that.audioContext.currentTime>that.source.buffer.duration){
                    that.source.stop(0);
                    that.playing = false;
                    clearInterval(timer);
                }
            }
        },100);
    },
    stop: function () {
        var that = this;
        that.source.stop(0);
        that.playing = false;
    }
};

調(diào)用方法:

var v=new Visualizer({
    url:"2.mp3",//audio地址 沒有寫兼容跨域的方法,所以不能跨域
    loop:false//是否循環(huán)
});
v.init();
v.play();
setInterval(function () {
    if(v.ready){
          console.log("ready!");
    } else if(v.loadFailed){
          console.log("加載失敗");
    }
    if (v.playing){ //playing判斷是否在播放
        console.log(v.frequency);//frequency是長(zhǎng)度為16的頻率值數(shù)組
    }
},100);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前些日子從@張?chǎng)涡裎⒉┨幍靡环萃扑](Front-end-tutorial),號(hào)稱最全的資源教程-前端涉及的所有知識(shí)...
    谷子多閱讀 4,477評(píng)論 0 44
  • 心碎 心痛 結(jié)局還不如不看 每次都有舍不得的人死去 換來一些東西 看到解憂好姐妹阿彩死去的時(shí)候就有點(diǎn)難過 然后昆彌...
    珺蕭閱讀 420評(píng)論 0 1
  • 尤優(yōu)一進(jìn)教室就看見季雅晴在墨小溪面前說話,兩個(gè)人貌似聊得還挺開心,氣就不打一出來,三步并作兩步,大跨步來到墨小溪面...
    Angel愛Bryce斌閱讀 456評(píng)論 0 0

友情鏈接更多精彩內(nèi)容