音频文件播放与暂停

/**
 * 播放音频文件
 * @param {string} id 唯一编码
 * @param {string} file 文件路径
 * @param {boolean} loop 是否循环播放
 * @param {number} volume 声音大小
 */
export const playAudio = (id: string, file: string, loop: boolean, volume = 1) => {
  const audioplayer = document.getElementById(id) as HTMLAudioElement;
  if (audioplayer != null) {
    audioplayer.play();
  } else if (file) {
    if (navigator.userAgent.indexOf('MSIE') > 0) { // IE
      const player: any = document.createElement('bgsound');
      player.id = id;
      player.src = file;
      player.volume = volume;
      player.setAttribute('autostart', 'true');
      if (loop) {
        player.setAttribute('loop', 'infinite');
      }
      document.body.appendChild(player);
    } else { // Other FF Chome Safari Opera
      const player = document.createElement('audio');
      player.id = id;
      player.volume = volume;
      player.setAttribute('autoplay', 'autoplay');
      if (loop) {
        player.setAttribute('loop', 'loop');
      }
      document.body.appendChild(player);
      const mp3 = document.createElement('source');
      mp3.src = file;
      mp3.type = 'audio/mpeg';
      player.appendChild(mp3);
    }
  }
};

export const stopAudio = (id) => {
  const player: any = document.getElementById(id);
  if (player != null) {
    player.pause();
    player.currentTime = 0;
  }
};

使用

	stopAudio('phoneNumberClick');
	playAudio('phoneNumberClick', '/resource/audios/press.wav', false);

    playAudio('audioplane', '/resource/audios/ringtone.mp3', true, volume);

移除所有的音频

const removeVideos = () => {
  // TODO
  const videos: any = document.querySelector('.videos');
  if (videos) {
    videos.querySelectorAll('video').forEach((item) => {
      item.pause();
    });
    videos.style.display = 'none';
  }
};

你可能感兴趣的:(javascript)