Css звуки this is

Play Sound on :hover

I’d argue that sounds are part of design and thus the ability to play/trigger it belongs in CSS, but alas, we’re not there yet. To play sounds when the mouse goes over a certain area, we’re going to need to rely on HTML5 or Flash. But nobody around here wants to deal with Flash right? So let’s do it with HTML5, which can play sound through its element (Firefox 3.5+, Chrome 3+, Opera 10.5+, Safari 4+, IE 9+). To get as much browser support as we can, we’ll do it like this with both an MP3 source (WebKit and IE) and an OGG source (Firefox and Opera).

  

If you insert the code exactly as above into a page, you won’t see or hear anything. If you want a little player element, make sure to use the controls attribute ( ). If you want it to play but not be seen, make sure to use the autoplay element ( ). Or both…

Our goal is to have the sound play when the mouse hovers over a certain element, like a menu item. Again unfortunately, we can’t tell an element what to do through CSS, so we’ll need JavaScript. To play the sound with JavaScript:

var audio = document.getElementsByTagName("audio")[0]; audio.play(); // or with an ID var audio = document.getElementById("mySoundClip"); audio.play();

Let’s use jQuery, just because it’s going to make selecting and dealing with events easier.

var audio = $("#mySoundClip")[0]; audio.play();

So to make this sound begin to play when the mouse hovers over a certain element:

var audio = $("#mySoundClip")[0]; $("nav a").mouseenter(function() < audio.play(); >);

The teaser page for the Goodfoot mobile app uses a similar technique to play weird groaning noises (via Dave Rupert) when you hover over the yeti dude. They do it by injecting a new audio element into the DOM everytime that yeti dude is hovered:

$("#speak").mouseenter(function() ").attr(< 'src':'audio/'+Math.ceil(Math.random() * 5)+'.mp3', 'volume':0.4, 'autoplay':'autoplay' >).appendTo("body"); >);

That could probably be improved a little, to support OGG as well. Not sure what the volume attribute is all about, that’s not spec nor supported anywhere I’ve seen. This is a modified from Jeffrey Way:

function addSource(elem, path) < $('').attr('src', path).appendTo(elem); > $("#speak").mouseenter(function()< var audio = $('', < autoPlay : 'autoplay' >); addSource(audio, 'audio/'+Math.ceil(Math.random() * 5)+'.mp3'); addSource(audio, 'audio/'+Math.ceil(Math.random() * 5)+'.ogg'); audio.appendTo('body'); >);

I’m totally fine with this approach, since it seems to work fine and that’s the bottom line. After the sound has been played once it seems to cache and play quickly, which is good.

Читайте также:  Print list for python

Another way to handle it would be to put all three audio elements onto the page right away.

    

Then randomly choose one to play:

Trials and Troubles: Overlapping Sounds

My original idea for playing with this was a navigation menu that played a little clicking sound while hovering over them. Immediately this uncovered a problem: you can hover over menu items triggering a .play() a lot faster than that sound can finish playing. A single audio element can’t play it’s own sound in an overlapping way. It just ignores further requests to .play() until it’s completed.

My first try was to use .pause() to stop the playing and then .play() again, but in my testing that doesn’t help much. It seems to honor the pause but then not the play in many cases.

The smoothest way I could find to do it was to duplicate the audio element for each menu item. That way each menu item has it’s own audio clip to play and the sounds can overlap

$("nav a") // loop each menu item .each(function(i) < if (i != 0) < // only clone if more than one needed $("#beep") .clone() .attr("id", "beep-" + i) .appendTo($(this).parent()); >$(this).data("beeper", i); // save reference >) .mouseenter(function() < $("#beep-" + $(this).data("beeper"))[0].play(); >); $("#beep").attr("id", "beep-0"); // get first one into naming convention

Источник

Воспроизведение звуков с помощью CSS

Эта статья рассказывает о способе, который позволяет воспроизводить звук на веб-странице с помощью CSS. Но я не рекомендую использовать его там, где проигрывание звукового контента можно реализовать с помощью и JavaScript.

Реализация

Воспроизведение звуков с помощью CSS основано на вставке аудиофайла в HTML-код в виде скрытого объекта и его проигрывании :

 embed < display: none; >button:active + embed  

Приведенный выше код использует тег . Но также можно применять :

Используя эту технику, около года назад я создал пианино на чистом HTML / CSS . Оно отлично работало, но сейчас оно больше не работает на CodePen.

В примере использует embed или object вместо audio, поэтому импортированный файл подвергается более строгим проверкам безопасности.

Согласно нормам политики контроля доступа к сторонним источникам (CORS) аудиофайл должен использовать тот же протокол и домен, что и страница, на которую он импортирован. Даже перевод звука в base64 больше не поможет. А чтобы его услышать, пользователям нужно разрешить воспроизведение звука на веб-странице в настройках браузера. Кроме этого теперь браузеры воспроизводят звуки только один раз.

Ограничения CORS можно обойти, если у вас есть контроль над серверами и файлами.

Почему так?

Теорию, лежащую в основе подобного поведения можно найти в определении тега . Если этот элемент становится потенциально активным , пользовательский агент должен поставить его задачу в очередь и выполнить ее.

По крайней мере, так должны вести себя все браузеры. Но они этого не делают.

Поддержка браузерами

Это работает в Opera и Google Chrome. Тем не менее, этот подход не будет работать в других браузерах на базе движка Chromium. В Safari, Internet Explorer или Microsoft Edge для Windows данная реализация также работать не будет. Браузер Firefox будет воспроизводить все звуки одновременно только при загрузке страницы.

В целом, это лишь забавный CSS-трюк. Но он не годится для практического применения.

Источник

Playing Sounds with CSS

CSS is the domain of styling, layout, and presentation. It is full of colors, sizes, and animations. But did you know that it could also control when a sound plays on a web page? This article is about a little trick to pull that off. It’s actually a strict implementation of the HTML and CSS, so it’s not really a hack. But… let’s be honest, it’s still kind of a hack. I wouldn’t recommend necessarily using it in production, where audio should probably be controlled with native

There are a few alternatives to playing sounds with CSS, but the underlying idea is the same: inserting the audio file as a hidden object/document within the web page, and displaying it whenever an action happens. Something like this:

 embed < display: none; >button:active + embed  

A quick note on the demo and this technique. I developed a small piano on CodePen just with HTML and CSS using this technique about a year ago. It worked great, but since then, some things have changed and the demo doesn’t work on CodePen anymore. The biggest change was related to security. As it uses embed or object instead of audio , the imported file is subject to stricter security checks. Cross-origin access control policies (CORS) force the audio file to be on the same protocol and domain as the page it is imported into. Even putting the sound in base64 will not work anymore. Also, you (and users) may need to activate autoplay on their browser settings for this trick to work. It is often enabled behind a flag. Another change is that browsers now only play the sounds once. I could have sworn that past browsers played the sound every time that it was shown. But that doesn’t appear to be the case anymore, which considerably limits the scope of the trick (and bares the piano demo almost useless). The CORS issue can be worked around if you have control over the servers and files, but the disabled autoplay is a per-user thing that is out of our control. View Demo

Whenever an embed element that was not potentially active becomes potentially active, and whenever a potentially active embed element that is remaining potentially active and has its src attribute set, changed, or removed or its type attribute set, changed, or removed, the user agent must queue a task using the embed task source to run the embed element setup steps for that element.

While it is clearer for object (the file is processed and run on render), we have this concept of “potentially active” for embed that may seem a bit more complicated. And while there are some additional conditions, it will run on initial render similarly as how it does with object .

As you can see, technically this is not a trick at all, but how all browsers should behave… although they don’t.

As with many of these hacks and tricks, the support of this feature is not great and varies considerably from browser to browser.

It works like a charm on Opera and Chrome, which means a big percentage of the browser market. However, the support is spotty for other Chromium-based browsers. For example, Edge on Mac will play the audio correctly, while the Brave browser won’t unless you have the latest version.

Safari was a non-starter, and the same can be said for Internet Explorer or Edge on Windows. Nothing close to working on any of these browsers.

Firefox will play all the sounds at once on page load, but then won’t play them after they are hidden and shown again. It will trigger a security warning in the console as the sounds attempt to be play “without user interaction,” blocking them unless the user approves the site first.

Overall, this is a fun trick with CSS but one of those “don’t do this at home” kind of things… which in software development, means this is the perfect thing to do at home. 🙂

Источник

Оцените статью