jQuery按ID选择当前播放的音频

时间:2018-08-06 11:51:23

标签: javascript jquery html css audio

经过一番谷歌搜索后,我发现以下代码可以选择当前播放的音频:

document.getElementsByTagName('audio').addEventListener('playing',function() { myfunction(); },false); 

但是我想在上面的代码中添加选择播放音频的功能,就像这样:

document.getElementsByTagName('audio').addEventListener('playing',function() { myfunction({ $(this).volume = 0.2 }); },false); 

实际上,我只想用一个滑块(输入类型=范围)控制每种声音。

var max = 100,
  min = 0,
  step = 1,
  output = $('#output').text(max);
$("#range-slider")
  .attr({
    'max': max,
    'min': min,
    'step': step,
    'value': max
  })
  .on('input change', function() {
    output.text(this.value);
  });
  window.SetVolume = function(val)
{
    var player = document.getElementById('audi');
    console.log('Before: ' + player.volume);
    player.volume = val / 100;
    console.log('After: ' + player.volume);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
song is playing, please wait...
<audio id="audi" controls autoplay>
  <source src="http://picosong.com/cdn/fa4d593f627cc8e4a23e5608cb92945b.mp3" type="audio/mpeg">
</audio>
<br>
<input type="range" id="range-slider" oninput="SetVolume(this.value)" onchange="SetVolume(this.value)">
<output id="output"></output>

1 个答案:

答案 0 :(得分:0)

您的mp3网址不适合我。链接可能已过期?将其替换为有效的网址后,您的代码即可正常工作。移动滑块可调整音频元素的音量。

var max = 100,
  min = 0,
  step = 1,
  output = $('#output').text(max);
$("#range-slider")
  .attr({
    'max': max,
    'min': min,
    'step': step,
    'value': max
  })
  .on('input change', function() {
    output.text(this.value);
  });
  window.SetVolume = function(val)
{
    var player = document.getElementById('audi');
    console.log('Before: ' + player.volume);
    player.volume = val / 100;
    console.log('After: ' + player.volume);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
song is playing, please wait...
<audio id="audi" controls autoplay>
  <source src="https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3" type="audio/mpeg">
</audio>
<br>
<input type="range" id="range-slider" oninput="SetVolume(this.value)" onchange="SetVolume(this.value)">
<output id="output"></output>