且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Html 5音频标签自定义控件?

更新时间:2023-10-14 22:57:34

你创建你的元素......

 < audio id =yourAudiopreload ='none'> 
< source src ='音频的网址'type ='audio / wav'/>
< / audio>
< a href =#id =audioControl> play!< / a>

并添加一些功能:

  var yourAudio = document.getElementById('yourAudio'),
ctrl = document.getElementById('audioControl');

ctrl.onclick = function(){

//更新按钮
var pause = ctrl.innerHTML ==='pause!';
ctrl.innerHTML =暂停? '玩!':'停顿!';

//更新音频
var method = pause? '暂停':'玩';
yourAudio [method]();

//防止默认操作
返回false;
};

现在,按钮只是简单的文本(play!或pause!)但你可以用CSS做任何你想做的事情。而不是设置 innerHTML ,请设置 className ,您可以轻松前往!


I feel like I'm taking crazy pills here because I can not figure out how to render the html 5 audio tag with custom controls.

I have this html so far, and it works no problem:

<audio controls preload='none'><source src='the url to the audio' type='audio/wav' /></audio>

How do I get it to display ONLY the play button, and perhaps when playing, show the pause button in it's place.

From what I read,

By default, the element will not expose any sort of player controls. You can create your own controls with plain old HTML, CSS, and JavaScript. The element has methods like play() and pause() and a read/write property called currentTime. There are also read/write volume and muted properties. So you really have everything you need to build your own interface.

If you don’t want to build your own interface, you can tell the

browser to display a built-in set of controls. To do this, just include the controls attribute in your tag.

But I can not find any examples of using custom controls. How do you get just the play button?

You create your elements like so...

<audio id="yourAudio" preload='none'>
    <source src='the url to the audio' type='audio/wav' />
</audio>
<a href="#" id="audioControl">play!</a>

And add some functionality:

var yourAudio = document.getElementById('yourAudio'),
    ctrl = document.getElementById('audioControl');

ctrl.onclick = function () {

    // Update the Button
    var pause = ctrl.innerHTML === 'pause!';
    ctrl.innerHTML = pause ? 'play!' : 'pause!';

    // Update the Audio
    var method = pause ? 'pause' : 'play';
    yourAudio[method]();

    // Prevent Default Action
    return false;
};

Right now, the button is just simple text ("play!" or "pause!"), but you could do just about anything you wanted with CSS. Instead of setting the innerHTML, set the className and you're good to go!