在Javascript中播放伴随随机图像的声音

时间:2013-10-31 15:54:53

标签: javascript html audio

我有一个像这样的随机图像生成器:

<head>

<script language="JavaScript">
function pickimg(){
    var imagenumber = 4 ;
    var randomnumber = Math.random() ;
    var rand1 = Math.round( (imagenumber-1) * randomnumber) + 1;
    images = new Array
    images[1] = "image1.jpg"
    images[2] = "image2.jpg"
    images[3] = "image3.jpg"
    images[4] = "image4.jpg"
    var image = images[rand1]
    document.randimg.src = image
    }
</script>

</head>

<body onLoad="pickimg()">

<a href="" onClick="pickimg();return false;"><body onLoad="pickimg()">

<a href="" onClick="pickimg();return false;"><IMG SRC="YOUR IMAGE" name="randimg" border=0 width="100%" height="100%"></a></a>

</body>

当显示image1.jpg时,我还想播放sound1.wav。当显示image2.jpg时,我还想播放sound2.wav,等等。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用您已实施的相同逻辑,您可以执行以下操作:

<body onLoad="pickimg()">
    <a href="" onClick="pickimg();return false;"><body onLoad="pickimg()">
    <a href="" onClick="pickimg();return false;"><IMG SRC="YOUR IMAGE" name="randimg" border=0 width="100%" height="100%"></a></a>
    <audio id="audioTag"></audio>
    <script>
        function pickimg() {
            var imagenumber = 4;
            var randomnumber = Math.random();
            var rand1 = Math.round((imagenumber - 1) * randomnumber) + 1;
            images = new Array
            images[1] = "image1.jpg"
            images[2] = "image2.jpg"
            images[3] = "image3.jpg"
            images[4] = "image4.jpg"
            var image = images[rand1];
            document.randimg.src = image

            var sounds = new Array
            sounds[1] = "sound1.wav"
            sounds[2] = "sound2.wav"
            sounds[3] = "sound3.wav"
            sounds[4] = "sound4.wav"
            var sound = sounds[rand1];
            audioTag.src = sound;
            audioTag.play();
        }
    </script>
</body>

这是未经测试的,并且有更好的方法可以做到这一点,但我使用了已经实现的逻辑,以使您更容易。

仅供参考 - “语言”属性多年未使用。