2013-02-02 117 views
3

如何为我的音频创建暂停功能?我已在下面的脚本中使用了播放功能。暂停网络音频API声音播放

http://pastebin.com/uRUQsgbh

function loadSound(url) { 
    var request = new XMLHttpRequest(); 
    request.open('GET', url, true); 
    request.responseType = 'arraybuffer'; 

    // When loaded decode the data 
    request.onload = function() { 

     // decode the data 
     context.decodeAudioData(request.response, function(buffer) { 
      // when the audio is decoded play the sound 
      playSound(buffer); 
     }, onError); 
    } 
    request.send(); 
} 

function playSound(buffer) { 
    sourceNode.buffer = buffer; 
    sourceNode.noteOn(0); 
} 

但我怎样才能暂停或停止呢?

+1

'sourceNode.noteOff(0);' – idbehold

回答

9

简短的回答是“你不能暂停它 - 你可以通过调用sourceNode.noteOff(0);来阻止它,就像idbehold所说的那样:”。

出于同样的原因,音频电缆上没有“暂停”按钮也无法暂停 - 因为数据一直在运行。你可以实现一个可以暂停的记录器节点,但是如果你没有取消暂停,它会在某个时候缓冲大量的数据。

实现此场景的常用方法是跟踪回放的位置(例如,通过记住开始时的位置),然后在想要暂停时记住该偏移量,然后调用noteOff(0),然后当你想重新开始播放时,创建一个指向同一个缓冲区的新节点,并调用带偏移量的noteOnGrain。

+4

不知道当我所做的一切都是解释API时,为什么你低调回答我的答案。 – cwilso

4

noteOff(0)的问题是它会破坏AudioNode,所以您将无法使用暂停音频。相反,您可以简单地断开sourceNode,这将有效地暂停音频。要恢复播放,只需重新连接即可。由于您的代码连接到sourceNodeanalyser

function pause() { 
    sourceNode.disconnect(); 
} 

function resume() { 
    sourceNode.connect(analyser); 
} 

希望帮助!

+3

这是Chrome的实现中的错误,实际上 - 不要依赖它继续作为“暂停”。 – cwilso

+1

cwilson是对的,这是错误的答案,将来无法正常工作。这是一个错误,并且在API中不受支持。 – AlexC

+0

@cwilso是否有这个bug的铬票?我试图通过断开和重新连接一个节点来实现“静音”功能,但只是意识到当断开连接时声音会恢复到原来的位置,而不是基于currentTime的上下文。谢谢! – Craig

0

在分配缓冲区之前,你已经创建了一个bufferSource可以使用的上下文。 创建bufferSource的方法是“createBufferSource”=> context.createBufferSource。在创建bufferSource之后,您使用“context.destination”=> source.connect(context.destination);创建了一个conexion。是所有的,玩到现在,使用起始(0)到现代的浏览器,以旧的浏览器是noteOn(0)

function loadSound() { 
    xhr = new XMLHttpRequest(); 
    xhr.open('GET', url, true); 
    xhr.responseType = 'arraybuffer'; 
    xhr.onload = function() { 
     /* Processing response data - xhr.response */ 
     /* Decoding audio data. */ 
     var context = new webkitAudioContext(); 
     context.decodeAudioData(xhr.response, function onSuccess (buffer) { 
      if (! buffer) { 
       alert('Error decoding file data.'); 
       return; 
      } 
      var source = context.createBufferSource(); /* Create SourceNode. */ 
      source.buffer = buffer; /* buffer variable is data of AudioBuffer type from the decodeAudioData() function. */ 
      source.connect(context.destination); /* Connect SourceNode to DestinationNode. */ 
      source.start(0); /* Play sound. */ 
     }, function onError (error) { 
      alert('Error decoding file data.'); 
     }); 

    }; 
    xhr.onerror = function() { 
     /* Handling errors */ 
     console.log('error'); 
    }; 
    xhr.send(); 
}