简体   繁体   English

Javascript:从单个HTML页面播放多个音频文件

[英]Javascript: play multiple audio files from a single HTML page

I'm new to Javascript (from a Python background) 我是Javascript的新手(来自Python背景)

I need an HTML page with several buttons, each of which will play 5 seconds of an audio file starting a specified point in time. 我需要一个带有几个按钮的HTML页面,每个按钮将在指定的时间点播放5秒的音频文件。

Here's my current approach: 这是我目前的做法:

 <audio id="audio_file_1"> <source src="path/to/file/audio_file_1.wav" type="audio/wav"> </audio><br> <audio id="audio_file_2"> <source src="path/to/file/audio_file_2.wav" type="audio/wav"> </audio><br> <button onclick="play_slice()" type="button">Play</button> <button onclick="play_slice()" type="button">Play</button> <script> function play_slice() { var x = document.getElementById("audio_file_1"); x.currentTime = 10; x.play(); setTimeout(function (){ x.pause(); }, 5000); } </script> 

Currently, 'audio_file_1' and the start time, 10 seconds, are hardcoded in the script. 目前,'audio_file_1'和开始时间10秒在脚本中是硬编码的。 How can I pass these as variables to the 'play_slice()' function, so that the first button plays the first audio file from an integer number of seconds? 如何将这些作为变量传递给'play_slice()'函数,以便第一个按钮从整数秒开始播放第一个音频文件?

Put some inputs in your HTML and read their values when the button is pressed : 在HTML中输入一些输入并在按下按钮时读取它们的值:

 <audio id="audio_file_1"> <source src="path/to/file/audio_file_1.wav" type="audio/wav"> </audio><br> <audio id="audio_file_2"> <source src="path/to/file/audio_file_2.wav" type="audio/wav"> </audio><br> <input type="number" name="time" id="time" value="10" /> <select id="track"> <option value="audio_file_1">audio 1</option> <option value="audio_file_2">audio 2</option> </select> <button onclick="play_slice()" type="button">Play</button> <button onclick="play_slice()" type="button">Play</button> <script> function play_slice() { var x = document.getElementById(document.getElementById("track").value); x.currentTime = +document.getElementById("time").value; x.play(); setTimeout(function (){ x.pause(); }, 5000); } </script> 

You will simply need to add an additional argument to your function as below. 您只需要在函数中添加一个额外的参数,如下所示。 And if it is not passed, a default value, 10 for instance, will be assigned 如果未通过,则将分配默认值(例如10)

<audio id="audio_file_1">
  <source src="path/to/file/audio_file_1.wav" type="audio/wav">
</audio><br>
<audio id="audio_file_2">
  <source src="path/to/file/audio_file_2.wav" type="audio/wav">
</audio><br>
<button onclick="play_slice('audio_file_1',10)" type="button">Play</button>        
<button onclick="play_slice('audio_file_2')" type="button">Play</button>        

<script>
  function play_slice(currentTime) { 
  var x = document.getElementById(audioId);
  x.currentTime = currentTime || 10;
  x.play();
    setTimeout(function (){
      x.pause();
      }, 5000);       
    } 
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM