Results 1 to 5 of 5

Thread: Play a sound on hyperink?

  1. #1
    Join Date
    Sep 2007

    Play a sound on hyperink?

    Hi guys

    I'm using this script to play a sound when a link is pressed (I'm viewing it in an iPad):

    <!--[ In the head section of the HTML ]-->
    <script type="text/javascript">
    	function play_single_sound() {
    <!--[ In the body section of the HTML ]-->
    <!--embedded audio-->
    div#audio {
    	display: none;
    	overflow: hidden;
    <div id="audio">
    	<audio id="audiotag" src="http://www.soundjay.com/button/sounds/button-4.mp3" autobuffer="autobuffer"></audio>
    <!--/embedded audio-->
    <a href="javascript:play_single_sound();">Next page</a>
    <!--[ Optional CSS ]-->
    It works just fine. However, I need to direct the user to another page after the sound is played. Is this possible? If so, how is it done?

    Any help would be fully appreciated.

    Best regards

    Rod from the UK

  2. #2
    Join Date
    Mar 2005
    Behind you...
    The <audio> element has an 'ended' event that you could use to trigger this. A simple event listener could trigger your redirect like so:

    document.getElementById('audiotag').addEventListener('ended', function() {
    	window.location.href = "http://www.some-new-url.com/and/stuff.html"
    }, false);
    Also, I feel like noting that none of this is really cross-browser compatible. The <audio> tag itself has some setbacks when viewed across multiple browsers (mainly a lack of support in older versions of IE, and file type compatibility in browsers that do support it). And the code above to set the event listener will not work in IE8 or lower (but given that the <audio> tag isn't supported there I didn't feel the need to add IE's old attachEvent() method).
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  3. #3
    Join Date
    Apr 2014
    Also, remember that Opera does not support mp3 file format for the <audio> tag. It only supports wav or ogg.

  4. #4
    First off, the riot act. Auto-playing noises on websites are annoying garbage that was on pretty much every 'top ten design failure' list of the previous decade. Someone viewing a website while rocking out to Motorhead, Skynrd, Van Halen (not van hagar) -- or wussing out to Celine and Miley - doesn't want your button sound blasting them just because they clicked on a link. It's going to be even more annoying since on something like an anchor you'll have to delay before you allow the new page to load, slowing down the user experience.

    THAT SAID, if this is a applet or maybe a game, THEN there might be a reason to do this... But it's going to take a LOT more work than you think.

    Your code as is has... issues. You're loading scripting only elements in the markup, it has no graceful degradation, and is markup hooking the scripting instead of the scripting hooking the markup.

    Really what you need here is a healthy dose of the "unwritten rule of JavaScript" -- if you can't make a page work without JavaScript FIRST, you likely have no business adding scripting to it.

    To that end, I would have a class to indicate that an anchor should play a sound, and make the rest of it a normal anchor.

    <a href="#" class="clickSound" rel="next">Next Page</a>

    Replacing # with wherever it is you want to go. (that REL is handy in browsers that will let you forward to the first 'next' on the page)...

    It is then a matter of isolating anchors with .clickSound on them, and attaching the method. I would load the audio by generating the element in the JS -- since there is no reason for it to exist in non-js UA's... hooking that sound's ondataloaded to apply the playback event to the anchors. Probably wrap it all in an anonymous function too so it has it's own isolated scope. The playback event would have to cancel bubbling, save the target HREF somehow, then hand off to the play() method. The sound's audio element would need (as Sup3rkirby rightly pointed out) a 'onended' handler, which would then change the window.location.href to the links target href.

    That would go a little something like this:

    (function(d) {
    		any browser that doesn't support these likely doesn't support
    		HTML 5 audio, so we can bomb out early here!
    	if (!d.getElementsByClassName || !window.addEventListener) return;
    		clickSound = d.createElement('audio'),
    		clickTarget = false;
    		If it doesn't have canPlayType, browser doesn't support audio,
    		so bomb out as there's no reason to continue; We also test for 
    		format support so we can choose the correct file type, if neither
    		of our desired audio types is present, bomb out.
    	if (typeof clickSound.canPlayType == 'function') {
    		if (clickSound.canPlayType('audio/mpeg')) {
    			clickFormat = 'mp3';
    		} else if (clickSound.canPlayType('audio/ogg')) {
    			clickFormat = 'ogg';
    		} else return;
    	} else return;
    		We just made these, no need to waste addEventListener on it.
    		Although we shouldn't have to, it's probably a good idea to
    		attach our handlers BEFORE setting the SRC.
    	clickSound.onended = function() {
    		if (clickTarget) window.location.href = clickTarget;
    	clickSound.onloadeddata = function() {
    		var anchors = d.getElementsByClassName('clickSound');
    		for (var t = 0; t < anchors.length; t++) anchors[t].addEventListener(
    			function(e) {
    				clickTarget = e.target.href;
    				if (e.preventDefault) e.preventDefault();
    				e.returnValue = false;
    	clickSound.src = 'sounds/button-4.' + clickFormat;
    	clickSound.style.display = 'none';
    Which should work in all modern browsers, as well as IE 9/newer. ...pay close attention to how I worded that.

    I put a live demo up here:

    As with all my examples the directory:

    Is unlocked for easy access to the gooey bits and pieces.

    Of course, one of the big hoots about this approach is that since we are detecting by browser capabilities and not markup specification, we can safely do this in a RECOMMENDATION doctype (non-HTML5) and still have 'valid markup'.

    Hope this helps -- I know it's a lot to take in.

  5. #5
    Oh, and a more versatile version might make that a normal function instead of anonymous, so you could pass it the file prefix (path exclusing extension) and the class to target, so you could have multiple different sounds on different links.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center



X vBulletin 4.2.2 Debug Information

  • Page Generation 0.12129 seconds
  • Memory Usage 2,881KB
  • Queries Executed 15 (?)
More Information
Template Usage (33):
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (3)bbcode_code
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (5)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (5)postbit
  • (5)postbit_onlinestatus
  • (5)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (72):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_postinfo_query
  • fetch_postinfo
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates