2017-02-22 23 views
0

我正在使用此功能創建聲音,該聲音在桌面和Android上運行良好,並且最初在iOS上使用touchevent啓動它時起作用。我需要以後用另一個聲音文件替換聲音,但是在iOS中它不會啓動 - 我假設因爲它需要另一個用戶交互來播放聲音。更改WebAudioAPI中的聲音而無需iOS上的用戶交互

這是一個耳機中的VR應用程序,所以這種用戶交互是不可能的。是否有另一種替代聲音或另一種非點擊用戶互動的方式,我可以像運動一樣使用?

我已經看到了這個http://matt-harrison.com/perfect-web-audio-on-ios-devices-with-the-web-audio-api/

似乎有另一種解決方案,但我不想預加載的所有文件(它們是合理的大,還有他們的10),這似乎這裏是一個要求 - 再加上我在代碼中使用暫停功能。有沒有簡單的方法呢?

var AudioContext = AudioContext || webkitAudioContext, context = new AudioContext(); 

function createSound(filename) { 
console.log('createSound()'); 

var url = cdnPrefix + '/' + filename; 
var buffer; 


context = new AudioContext(); 

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

// Decode asynchronously 
request.onload = function() { 
    context.decodeAudioData(request.response, function(b) { 
     buffer = b; 
     play(); 
    }); 
} 
request.send(); 


var sourceNode = null, 
    startedAt = 0, 
    pausedAt = 0, 
    playing = false, 
    volume = context.createGain(); 

var play = function() { 

    if(playing || !buffer) 
     return; 

    var offset = pausedAt; 

    sourceNode = context.createBufferSource(); 
    sourceNode.connect(context.destination); 
    sourceNode.connect(volume); 
    volume.gain.value = 1; 

    sourceNode.buffer = buffer; 
    sourceNode.start(0, offset); 
    sourceNode.onended = onEnded; 

    sourceNode.onstatechange = onStateChange; 
    sourceNode.onloaded = onLoaded; 
    //sourceNode.loop = true; 
    startedAt = context.currentTime - offset; 
    pausedAt = 0; 
    playing = true; 
    $(document).trigger("voiceoverPlay"); 

    if(isPaused == true) 
     pause(); 
}; 

function onEnded(event){ 
    $(document).trigger("voiceoverEnded"); 
    play(); 
} 

function onStateChange(event){ 
    console.log('onStateChange',event); 
} 

function onLoaded(event){ 
    console.log('onLoaded',event); 
} 


var pause = function() { 
    var elapsed = context.currentTime - startedAt; 
    stop(); 
    pausedAt = elapsed; 
    $(document).trigger("voiceoverPause"); 
}; 

var stop = function() { 
    if (sourceNode) { 
     sourceNode.disconnect(); 
     if(playing === true) 
      sourceNode.stop(0); 
     sourceNode = null; 
    } 
    pausedAt = 0; 
    startedAt = 0; 
    playing = false; 
}; 

var getPlaying = function() { 
    return playing; 
}; 

var getCurrentTime = function() { 
    if(pausedAt) { 
     return pausedAt; 
    } 
    if(startedAt) { 
     return context.currentTime - startedAt; 
    } 
    return 0; 
}; 

var setCurrentTime = function(time) { 
    pausedAt = time; 
}; 

var getDuration = function() { 
    return buffer.duration; 
}; 

return { 
    getCurrentTime: getCurrentTime, 
    setCurrentTime: setCurrentTime, 
    getDuration: getDuration, 
    getPlaying: getPlaying, 
    play: play, 
    pause: pause, 
    stop: stop 
}; 

}

回答

0

你需要爲每一個聲音的觸摸事件。

我結束了使用SoundJS,這是好得多。