有一个js-脚本:
<script>
function start1() {
var audio = new Audio();
audio.src = URL.createObjectURL(document.getElementById('f1').files[0]);
audio.autoplay = true;
}
function start2() {
var audio = new Audio();
audio.src = URL.createObjectURL(document.getElementById('f2').files[0]);
audio.autoplay = true;
}
...
function stop() {
var audio = new Audio();
audio.stop();
}
</script>和html代码:
<body>
<input type="file" id="f1"></input>
<input type="file" id="f2"></input>
...
<button onmousedown="start1()" onmouseup="stop()">1</button>
<button onmousedown="start2()" onmouseup="stop()">2</button>
...通过脚本可以理解,他播放一个声音文件,通过使用表单文件加载。
但是有两个问题:
1)要求声音只在事件按下(按下鼠标)时播放,并在释放鼠标按钮(onmouseup)时停止。现在声音被播放到最后,不管你是否点击鼠标按钮并放开它(因为这个条件没有测试)。
2)还需要创建脚本的简化版本,因为处理的函数应该是16块,但不是手动注册相同的每个函数。您必须创建一个生成的脚本,该脚本将处理id的N号(start1、start2等、f1、f2等)。
帮助修改代码,也可以完全编码jquery。这并不重要。
谢谢。
发布于 2015-05-20 18:40:16
您可以使用局部变量,您只需要一个标识符,以找到音频元素以后。您还需要将音频元素附加到DOM中。
此外,您还必须使用pause()而不是stop()。
<script>
function start(id, source) {
var aud = document.getElementById(id);
if (aud) {
aud.parentNode.removeChild(aud);
}
var audio = new Audio();
audio.setAttribute("id", id);
audio.src = URL.createObjectURL(document.getElementById(source).files[0]);
document.body.appendChild(audio);
audio.autoplay = true;
}
function stop(id) {
var aud = document.getElementById(id);
aud.pause();
}
</script>
<input type="file" id="f1"></input>
<input type="file" id="f2"></input>
<button onmousedown="start('1', 'f1')" onmouseup="stop('1')">1</button>
<button onmousedown="start('2', 'f2')" onmouseup="stop('2')">2</button>发布于 2015-05-20 17:58:56
这应该有效(未经测试):
`<script> var a1 = new Audio(); var a2 = new Audio(); function start1() { a1.src = URL.createObjectURL(document.getElementById('f1').files[0]); a1.autoplay = true; } function start2() { a2.src = URL.createObjectURL(document.getElementById('f2').files[0]); a2.autoplay = true; } function stop() { a1.stop(); a2.stop(); } </script>`https://stackoverflow.com/questions/30356782
复制相似问题