玩audioContext

时间:2015-07-22 23:03:32

标签: javascript webkitaudiocontext audiocontext

受这个SO answer的启发,我有这个代码,它可以工作,但它弹出并且听起来不是那么平滑。

$('.btn').each(initDraggable);
function initDraggable() {
	var param = {}
	param.drag = drag
	param.stop = stopper
	$(this).draggable(param)
}
var Variables = {}
Variables.Frequency = 0
function drag(myEvent,myUI) {
	var Frequency = myUI.position.left + 100
	var Duration = 5000
	if (Math.abs(Variables.Frequency-Frequency) > 25) {
		if (typeof(Variables.osc) === 'undefined') {
		} else {
			Variables.osc.stop(0)
		}
		Variables.Frequency = Frequency
		Oscillator(Frequency,Duration)
	}
}
function stopper() {
	Variables.osc.stop(0)
}


Variables.ctx = new(window.audioContext || window.webkitAudioContext)
function Oscillator(argFrequency,argDuration) {
	Variables.osc = Variables.ctx.createOscillator()
	Variables.osc.type = 0
	Variables.osc.connect(Variables.ctx.destination)
	Variables.osc.frequency.value = argFrequency
	Variables.osc.start(0)
	setTimeout(myTimeout,argDuration)
	function myTimeout() {
		Variables.osc.stop(0)
	}
}
<link rel="stylesheet" href="//cdn.jsdelivr.net/bootstrap/latest/css/bootstrap.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/jquery.ui/latest/jquery-ui.min.css">
<span class="btn btn-primary">Drag me</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/bootstrap/latest/js/bootstrap.js"></script>
<script src="//cdn.jsdelivr.net/jquery.ui/latest/jquery-ui.min.js"></script>
<script src="//cdn.jsdelivr.net/jquery.ui.touch-punch/latest/jquery.ui.touch-punch.js"></script>

问:有没有一种简单的方法让它听起来更平滑一点?

1 个答案:

答案 0 :(得分:1)

没有必要在update()上重新创建oscillator,我认为这是导致流行音乐的原因。 但是您可以更改已启动drag的{​​{1}},这样您就可以通过拖动frequency value创建振荡器,在oscillator上停止它,然后只需更改start上的频率值。像这样:

&#13;
&#13;
stop
&#13;
drag
&#13;
&#13;
&#13;