如何才能无延迟地连续播放音频?

问题描述 投票:0回答:1

我正在尝试制作一款游戏,其中有音乐(就像大多数游戏一样)。然而,更改曲目甚至循环播放同一曲目往往会带来非常轻微的延迟。我想使用纯原生 Javascript 删除它。

我试过这个:

// Sets an object with music URLs
const mus = {
    'Surface': "https://codeberg.org/NerdB0I/dungeoncrawlerost/raw/branch/main/mus/Surface.wav",
    'Deeper': "https://codeberg.org/NerdB0I/dungeoncrawlerost/raw/branch/main/mus/Deeper.wav"
} 
// This ensures that music will play and wait for each other using Promises 
function musPlay(name='') {
     return new Promise(resolve => {
         let audio = new Audio(mus[name]);
         audio.onended = () => resolve();
         audio.play();
     });
 }  
// This runs once everytime the song ends and plays a new song based on the variable currSong 
let currSong = 'Surface'; 
async function run() {
     await musPlay(currSong);
     run();
} 
run();  
// This allows you to press keys to change the song (and to see what key pressed) 
// I do not mind that the song continues playing after keydown, I just need it to set the currSong variable for when the files end 
window.addEventListener('keydown', (event) => {
     if (event.key == 'a') {
         currSong = 'Surface';
     } else if (event.key == 'd') {
         currSong = 'Deeper';
     }
     document.getElementById('body').innerHTML = event.key;
});

我的Liveweave 如果这只是 Liveweave 的问题而不是代码的问题,请告诉我。

编辑:固定文件格式
编辑:这更多的是一个附加说明:我将 body 标签设置为具有“body”的 id,以防此处不清楚

javascript audio delay
1个回答
0
投票

每次播放新音频文件时创建新的音频元素都会暂停,因为音频未加载。通过加载所有音频文件来启动脚本,然后使用相同的音频元素,而不是每次都创建一个。

// Sets an object with music URLs
let mus = {
  'Surface': "https://codeberg.org/NerdB0I/dungeoncrawlerost/raw/branch/main/mus/Surface.wav",
  'Deeper': "https://codeberg.org/NerdB0I/dungeoncrawlerost/raw/branch/main/mus/Deeper.wav"
};

// This runs once everytime the song ends and plays a new song based on the variable currSong
let currSong = 'Surface';

let audiopromises = Object.keys(mus).map(key => {
  return new Promise(resolve => {
    let audio = new Audio();
    audio.addEventListener('canplay', e => {
      resolve({key: key, elm: e.target});
    });
    audio.addEventListener('ended', e => {
      musPlay();
    });
    audio.src = mus[key];
  });
});

Promise.all(audiopromises).then(audio_arr => {
  mus = audio_arr;
  musPlay();
});

function musPlay(){
  let audio = mus.find(audio_obj => audio_obj.key == currSong);
  audio.elm.play();
}

document.addEventListener('keydown', (event) => {
  if (event.key == 'a') {
    currSong = 'Surface';
  } else if (event.key == 'd') {
    currSong = 'Deeper';
  }
  document.body.innerHTML = event.key;
});

© www.soinside.com 2019 - 2024. All rights reserved.