gpt4 book ai didi

javascript - 在 iOS 上无需用户交互即可更改 Web Audio API 中的声音

转载 作者:行者123 更新时间:2023-11-28 04:57:41 25 4
gpt4 key购买 nike

我使用这个函数来创建一个声音,它在桌面和 Android 上运行良好,并且当我使用 touchevent 启动它时,它最初在 iOS 上运行。我稍后需要用另一个声音文件替换声音,但是在 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
};

}

最佳答案

每个声音都需要一个触摸事件。

我最终使用了 SoundJS,它要好得多。

关于javascript - 在 iOS 上无需用户交互即可更改 Web Audio API 中的声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42404361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com