如何在javascript中的audioSourceNode上实现播放/暂停按钮?

时间:2015-06-23 12:55:50

标签: javascript audio

我在使用JavaScript在此SourceNode上实现简单的播放和暂停按钮时遇到了麻烦。

这是我的audioManipulater.js文件,所有内容都在index.php上查看,并在style.css上设置样式。

回到我的js文件。如果你看一下源的第一行的_visualize方法。在方法中,audioBufferSourceNode保存已加载的文件。

在第13行,音频节点上正在使用start()stop()方法。如何从库中获取audioBufferSourceNode的引用,以便我可以调用这些方法以某种方式播放和暂停声音?。

 _visualize: function(audioContext, buffer) {
    var audioBufferSourceNode = audioContext.createBufferSource(),
        analyser = audioContext.createAnalyser(),
        that = this;
    //connect the source to the analyser
    audioBufferSourceNode.connect(analyser);
    //connect the analyser to the destination(the speaker), or we won't hear the sound
    analyser.connect(audioContext.destination);
    //then assign the buffer to the buffer source node
    audioBufferSourceNode.buffer = buffer;
    //play the source
    if (!audioBufferSourceNode.start) {
        audioBufferSourceNode.start = audioBufferSourceNode.noteOn //in old browsers use noteOn method
        audioBufferSourceNode.stop = audioBufferSourceNode.noteOff //in old browsers use noteOn method
    };
    //stop the previous sound if any
    if (this.animationId !== null) {
        cancelAnimationFrame(this.animationId);
    }
    if (this.source !== null) {
        this.source.stop(0);
    }
    audioBufferSourceNode.start(0);
    this.status = 1;
    this.source = audioBufferSourceNode;
    audioBufferSourceNode.onended = function() {
        that._audioEnd(that);
    };
    this._updateInfo('Playing ' + this.fileName, false);
    this.info = 'Playing ' + this.fileName;
    document.getElementById('fileWrapper').style.opacity = 0.2;
    this._drawSpectrum(analyser);
 },

我将在我的代码中编辑index.php&如果需要,可根据要求提供style.css。

EDIT 完整代码:

https://jsfiddle.net/4hty6kak/1/

由于某些原因,可视化工具无法在jsfiddle上运行,因此这里有一个实时工作演示的链接:

http://wayou.github.io/HTML5_Audio_Visualizer/

1 个答案:

答案 0 :(得分:2)

这是一个范围问题。来自MDN entry about variable declarations

  

var声明的变量的范围是它的当前执行上下文,它是封闭函数,或者对于在任何函数外声明的变量,是全局的。

     

在执行赋值时,为未声明的变量赋值会隐式地将其创建为全局变量(它将成为全局对象的属性)。

当您声明变量如var audioBufferSourceNode = ...时,您正在使其成为_visualize方法的局部变量,这就是您无法从访问它的原因离开图书馆

你能做什么:

  1. 删除该变量声明的var关键字:

    audioBufferSourceNode = audioContext.createBufferSource()
    
  2. 全局声明变量(根据上面的解释,此步骤是可选的,因为变量将隐式创建为全局变量)。

  3. 有了这个,你会使audioBufferSourceNode成为一个全局变量,这意味着某些风险(例如:可能与其他变量发生冲突,可能会被其他任何方法操纵,维护更难调试,如果有错误)。

    您应该考虑以下@Palpatim的建议,将变量封装在模块中,并创建一个访问器,以便您可以从模块本身外部获取和操作它。