我正在努力让这个基本的淡入/淡出Web音频代码与SoundCloud一起使用。似乎gainNode.gain.linearRampToValueAtTime
函数被绕过(即播放开始并以gain.volume = 1.0结束。)
代码需要与iOS移动版Safari webkit一起使用。
包含CSS:
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,600' rel='stylesheet' type='text/css'>
HTML关注:
<div id="wrapper">
<div id="content">
<div class="post">
<h2>Fading in a Soundcloud Track</h2>
</p>
</div>
</div>
</div>
JS关注:
<script>
var audioCtx = new (window.AudioContext ||
window.webAudioContext ||
window.webkitAudioContext)();
var audio = new Audio();
var url = 'https://api.soundcloud.com/tracks/179612876/stream' + '?client_id=<MY_ID>';
audio.src = url;
audio.preload = true;
audio.load();
audio.addEventListener('canplay', function(){
var currTime = audioCtx.currentTime;
var duration = 30;
var fadeTime = 6;
var gainNode = audioCtx.createGain();
gainNode.gain.value = 0.0;
var source = audioCtx.createMediaElementSource(audio);
source.connect(gainNode);
gainNode.connect(audioCtx.destination);
// Then fade in
gainNode.gain.linearRampToValueAtTime(0.0, currTime);
gainNode.gain.linearRampToValueAtTime(1.0, currTime + fadeTime);
// Then fade it out.
gainNode.gain.linearRampToValueAtTime(1.0, currTime + duration-fadeTime);
gainNode.gain.linearRampToValueAtTime(0.0, currTime + duration);
//source.connect(audioCtx.destination);
source.mediaElement.play();
},false);
</script>
答案 0 :(得分:1)
&#34; gainNode.gain.value = 0.0;&#34;实际上并没有在调度程序中设置调度点,它只是设置当前值。由于调度程序中没有起始点,因此当它到达第一个调度点时(即时间currTime + fadeTime),它会跳起来。试试这个:
gainNode.gain.setValueAtTime(0.0, currTime);
gainNode.gain.linearRampToValueAtTime(1.0, currTime + fadeTime);
// Then fade it out.
gainNode.gain.setValueAtTime(1.0, currTime + duration-fadeTime);
gainNode.gain.linearRampToValueAtTime(0.0, currTime + duration);
(并且不要设置gain.gain.value)。