简体   繁体   English

使用HTML5和JavaScript播放/暂停音频按钮

[英]Play/pause audio button using HTML5 and JavaScript

I am trying to incorporate sound effects into a HTML5 based digital comic book which will be published for iPad only. 我正在尝试将声音效果整合到基于HTML5的数字漫画书中,该漫画书仅适用于iPad。 I want to use a simple play/pause button. 我想使用一个简单的播放/暂停按钮。 I have been playing around all day but I am still struggling with my limited JavaScript knowledge. 我整天都在玩游戏,但是我仍然在有限的JavaScript知识方面苦苦挣扎。 Here's the link to the comic and a functionality spec: 这是漫画和功能说明的链接:

http://spiritdigital.co.uk/outpost/issue-interactive/05.html http://spiritdigital.co.uk/outpost/issue-interactive/05.html

I want to: 我想要:

  • Have a clickable area over a particular scene (in this case, the car scene) 在特定场景(本例中为汽车场景)上有一个可点击的区域
  • On click, a sound plays and the 'play' icon changes to a pause icon 单击时,声音播放,“播放”图标变为暂停图标
  • On second click (when sound is playing) the sound pauses and icon switches back to play 第二次单击(播放声音时),声音暂停,图标切换回播放
  • If sound ends, icon changes back to play 如果声音结束,图标将变回播放状态

So far, I have the clickable area and the sound plays when the area is clicked but I need your help for the rest. 到目前为止,我有可单击的区域,单击该区域时会播放声音,但剩下的我需要您的帮助。

<audio id="myaudio">
    <source src="song.ogg" type="audio/ogg" />
    <source src="song.mp3" type="audio/mpeg" />
    Your browser does not support the audio element.
</audio>

Now to play the song : 现在播放歌曲:

var audio = document.getElementById('myaudio');
audio.play();

Pause: 暂停:

audio.pause();

To change the background image of your div : 更改div的背景图片:

var control = document.getElementById('yourdiv');
control.style.backgroundImage = 'pathtoanotherimage';

Here's what you want: DEMO 这就是您想要的: 演示

Basically there's two events that fire, play and pause, when you do the respective action. 基本上,执行相应的操作时会触发,播放和暂停两个事件。 I'm just binding to these to toggle the button image (in this case I just change the background-position as it's an image sheet). 我只是绑定到这些按钮上来切换按钮图像(在这种情况下,我只是更改背景位置,因为它是图像表)。

Any questions let me know. 有任何问题让我知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM