2016-08-16 64 views
0

这里是我的代码:网络音频API不移动工作的iOS

$(document).ready(function(){ 

var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); 
var oscillator = audioCtx.createOscillator(); 
var gainNode = audioCtx.createGain(); 
oscillator.connect(gainNode); 
gainNode.connect(audioCtx.destination); 
oscillator.type = 'sine'; 
gainNode.gain.value = 0; 
oscillator.start(); 

document.addEventListener("touchmove", function(e) { 
    e.preventDefault(); 
    var touch = e.touches[0]; 
    var x = touch.pageX; 
    var y = touch.pageY; 
    x = Math.round(x); 
    y = Math.round(y); 

    x = mRound(x, 20); 
    y = mRound(y, 10); 

    $("#coords").text(x + ", " + y); 

    gainNode.gain.value = x/10; 
    oscillator.frequency.value = y; 

}, false); 

}); 

function mRound(n, m){ 

if(n > 0) 
    return Math.ceil(n/m) * m; 
else if(n < 0) 
    return Math.floor(n/m) * m; 
else 
    return m; 

} 

这个工程在Chrome和Firefox浏览器在Android,但在iOS上的Safari或Chrome没有播放声音。网络音频api确实可以在safari中工作,因为我已经使用更简单的脚本对其进行了测试,并且'touchmove'似乎可以工作,因为坐标出现在#coords中。

谢谢。

回答

0

我正在处理类似的问题。当涉及到“自动启动”音频的可能性时,iOS上的WebKit非常挑剔。

对 “touchstart” 事件引发AudioContext的伎俩在我的iPhone SE与iOS 9.1.1:

$(document).ready(function(){ 
    var oscillator, gainNode, audioCtx; 

    var initOnce = false; 

    document.addEventListener("touchstart", function(e) { 
    if (!initOnce){ 
     initOnce = true; 
     audioCtx = new (window.AudioContext || window.webkitAudioContext)(); 
     oscillator = audioCtx.createOscillator(); 
     gainNode = audioCtx.createGain(); 
     oscillator.connect(gainNode); 
     gainNode.connect(audioCtx.destination); 
     oscillator.type = 'sine'; 
     gainNode.gain.value = 0; 
     oscillator.start(); 
    } 
    }); 

    document.addEventListener("touchmove", function(e) { 
     e.preventDefault(); 
     var touch = e.touches[0]; 
     var x = touch.pageX; 
     var y = touch.pageY; 
     x = Math.round(x); 
     y = Math.round(y); 

     x = mRound(x, 20); 
     y = mRound(y, 10); 

     $("#coords").text(x + ", " + y); 

     gainNode.gain.value = x/10; 
     oscillator.frequency.value = y; 

    }, false); 

}); 

function mRound(n, m){ 

if(n > 0) 
    return Math.ceil(n/m) * m; 
else if(n < 0) 
    return Math.floor(n/m) * m; 
else 
    return m; 

}