Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
827 views
in Technique[技术] by (71.8m points)

audio - Javascript play sound on hover. stop and reset on hoveroff

function EvalSound(soundobj) {
    var thissound=document.getElementById(soundobj);
    thissound.currentTime = 0;  
    thissound.Play();
}

function StopSound(soundobj) {
    var thissound=document.getElementById(soundobj);
    thissound.Stop();
}

This is my code to play a audio file,

onmouseover="EvalSound('sound1')" onmouseout="StopSound('sound1')"

It is currently working on hover, however when i go back to the image that it plays under it doesnt go back to the beginning, it continues playing

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The <embed> tag is the old way to embed multimedia. You really ought to be using the new HTML5 <audio> or <video> tags as they are the preferred and standardized way to embed multimedia objects. You can use the HTMLMediaElement interface to play, pause, and seek through the media (and lots more).

Here is a simple example that plays an audio file on mouseover and stops it on mouseout.

HTML:

<p onmouseover="PlaySound('mySound')" 
    onmouseout="StopSound('mySound')">Hover Over Me To Play</p>

<audio id='mySound' src='http://upload.wikimedia.org/wikipedia/commons/6/6f/Cello_Live_Performance_John_Michel_Tchaikovsky_Violin_Concerto_3rd_MVT_applaused_cut.ogg'/>

Javascript:

function PlaySound(soundobj) {
    var thissound=document.getElementById(soundobj);
    thissound.play();
}

function StopSound(soundobj) {
    var thissound=document.getElementById(soundobj);
    thissound.pause();
    thissound.currentTime = 0;
}

For more information, check out the MDN guide for embedding audio and video


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...