下面的代码生成并循环一些.ogg文件的随机数量的迭代。它们会在页面加载后立即播放。
注释掉的位是我尝试添加“开始”按钮。我在这里做错了什么,如何用按钮而不是页面加载来启动呢?
(另外:我怀疑将php和javascript结合起来是不好的做法。我这样做是因为php中的随机化非常简单,而且我还是js / jquery的新手。)
(编辑:请参阅下面的编辑。我只是忘了关闭标签。)
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
$randC = rand(2,4);
$C = $randC * 4;
$G = $C / 2;
echo "
<script type=\"text/javascript\">
$(document).ready(function()
{
// $(\"#start\").click(function()
// {
var time = 0;
var riff_time = 2920;
var base = 'riff';
for(i = 0; i < $C; i++)
{
var id = base + ((i + 1) );
window.setTimeout (\"document.getElementById('\" + id + \"').play()\", time);
time += riff_time;
}
var timeG = 0;
var riff_time = 2920;
var baseG = 'riffG';
for(iG = 0; iG < $G; iG++)
{
var idG = baseG + ((iG + 1) );
window.setTimeout (\"document.getElementById('\" + idG + \"').play()\", timeG);
timeG += riff_time;
// }
} // EDIT: This should be }); ... that fixes it.
});
</script>
"?>
<style type="text/css">
</style>
</head>
<body style="background-color: #999;">
<!--<button id="start">Start</button>
<br> -->
<?php
echo "C:<br>";
for ($i=1; $i<= $C; $i++) {
echo '<audio controls id="riff'.$i.'">
<source src="loopC.ogg" type="audio/ogg">
</audio>';
}
echo "<br>G:<br>";
for ($i=1; $i<= $G; $i++) {
echo '<audio controls id="riffG'.$i.'">
<source src="loopG.ogg" type="audio/ogg">
</audio>';
}
?>
</body>
</html>
答案 0 :(得分:0)
您可以将一个班级start
以及data-id
添加到开始按钮。
所以你的html for start按钮就像是,
<img src="start-button.jpg" class="start" data-id="riff1">
//So this is start button for audio elementwith id riff1.
这将如何运作?
$('.start').click(function(){
$("#"+$(this).data('id')).play(); //This should do.
}
是的,你的php文件应该是这个的类型,
<!DOCTYPE html>
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
$randC = rand(2,4);
$C = $randC * 4;
$G = $C / 2;
<script type="text/javascript">
$(document).ready(function()
{
// $("#start").click(function()
// {
var time = 0;
var riff_time = 2920;
var base = 'riff';
<?php for(i = 0; i < $C; i++)
{
echo " var id = base + ((i + 1) );
window.setTimeout (\"document.getElementById('\" + id + \"').play()\", time);
time += riff_time; ";
}
?>
var timeG = 0;
var riff_time = 2920;
var baseG = 'riffG';
<?php for(iG = 0; iG < $G; iG++)
{
echo " var idG = baseG + ((iG + 1) );
window.setTimeout (\"document.getElementById('\" + idG + \"').play()\", timeG);
timeG += riff_time; ";
// } ?>
}
});
</script>
<style type="text/css">
</style>
</head>
<body style="background-color: #999;">
<!--<button id="start">Start</button>
<br> -->
<?php
echo "C:<br>";
for ($i=1; $i<= $C; $i++) {
echo '<audio controls id="riff'.$i.'">
<source src="loopC.ogg" type="audio/ogg">
</audio>';
}
echo "<br>G:<br>";
for ($i=1; $i<= $G; $i++) {
echo '<audio controls id="riffG'.$i.'">
<source src="loopG.ogg" type="audio/ogg">
</audio>';
}
?>
</body>
</html>