Results 1 to 8 of 8

Thread: help using javascript using a random file

  1. #1
    Join Date
    Oct 2011
    Hamilton, Ontario

    help using javascript using a random file

    so what I am trying to do is create a function does the following three things each time it is run:
    1. pick a random sound file from an array and play it twice
    2. remove the played file from the list in the array
    3. when there is only one file left, restore all original values to the array so that the process can start over.

    at this point I don't know what my mistake is but the way it is coded here, it's not doing anything at all... I'm assuming I've made several syntax mistakes.

    <script type="text/javascript" >
    qintup = array["file1","file2", "file3", "file4"];

    function select(){
    click = 3;
    s1 = qintup[Math.floor(Math.random * click)];
    document.getElementById('object').innerHTML =
    "<embed src=\"sounds/int/" + s1 + ".wav\" style=\"display:none;\" autostart=\"true\" loop=\"2\" />";
    if (click<=3 && click>0) {
    click -= 1;
    else {
    qintup = array["file1","file2", "file3", "file4"];
    click = 3;


    and the HTML:
    <form >
    <label>Click to hear random selection:</label><button onclick="select()">Play Interval</button>
    <span id="object" style="display:none;"><a>.</a></span>

  2. #2
    Join Date
    Dec 2005


    I'm not sure what the <embed> tag does in the .innerHTML, but since that's what you wanted, that's what I kept.
    Modify is necessary for your needs.

    The randomizing of the array doesn't appear as random with only 4 selections, but un-comment the alert to see the actions.

    Modify the information in front of the <span> display (only in to show that <embed> tag would be called).

    <!DOCTYPE html>
    <html lang="en">
    <meta charset="utf-8" />
    <title> Untitled </title>
    <form onsubmit="return false">
    Click to hear random selection:
    <button onclick="select()"> Play Interval </button>
    <span id="spanObject"></span> 
    <script type="text/javascript" >
    var qintup = ["file1","file2", "file3", "file4"];
    var playFiles = [].concat(qintup);
        playFiles.sort(function() {return 0.75 - Math.random()}) //Array elements now scrambled
    function select() {
      if (playFiles.length-1 < 0) {
        playFiles = [].concat(qintup);
        playFiles.sort(function() {return 0.75 - Math.random()}) //Array elements now scrambled
    //  alert(playFiles.length+' : '+playFiles);  // for testing
      var s1 = playFiles.pop();
      var str = "<embed src='sounds/int/" + s1 + ".wav' autostart='true' loop='2' />";
      document.getElementById('spanObject').innerHTML = playFiles.length+' : '+s1+' : '+str;  // for testing

  3. #3
    Join Date
    Oct 2011
    Hamilton, Ontario
    ok i think i see how you switched around the order of operations there... but how does "function() {return 0.75 - Math.random()}" scramble the array? Math.random() just calls picks a random number between 0 and 1 right? thats what i was taught. (That's why I'm confused about the 0.75 part) what if I wanted to work with a much larger number of values, like putting over 100 different elements in the array?

  4. #4
    Join Date
    Dec 2005
    No changes needed except to the contents of your array.

    The use of 0.5 ir 0.75 does not matter as to the action of the sort function.
    0.75 gives just a bit more random results.

  5. #5
    Join Date
    Oct 2011
    Hamilton, Ontario
    okay.. thanks.. the only issue I'm having now is that the code i was using to play the sound file was not working so I tried this an it's still not working (some generic terms used):

    html: <button onclick="select('q1')"> Play Interval </button>
    <embed src="" id="q1" style="display:none;" autostart="false" loop="2" />


    function select(sound)
    ***other code***
    document.getElementById(sound).setAttribute('src', 'folder/folder/' + s1 + '.wav');

    what am i missing?

  6. #6
    Join Date
    Dec 2005


    Perhaps some other forum member can help because I know nothing about playing music files with the <embed...> tag.

  7. #7
    Join Date
    Jan 2010
    I donít know if it is a quirk of the embed tag or not but if you try to hide the embedded object none of its controls will work.

    I have tried to hide it using display:none and visibility:hidden both have the same effect, none of the controls are accessible from the script.

    The only way I found for to get it to hide the player and still get it to work was by sticking it out of sight on the left side of the screen

          <style type="text/css">
          position   : absolute; 
          top        : 0px;
          left       : -500px;
          <script type="text/javascript">
       function playSound(){
          <embed id="sound" src="MySong.mp3" autostart="false"></embed>
          <input type="button" onclick="playSound()" value="Play Sound">

    That said this works in IE and Opera on my machine because I have the quicktime player installed if I didnít have the plugin I wouldnít be able to play the sounds at all, it is worth noting that not every browser has an audio plugin installed.

    Hope this helps


  8. #8
    Join Date
    Jul 2008
    urbana, il
    Quote Originally Posted by JMRKER View Post
    No changes needed except to the contents of your array.

    The use of 0.5 ir 0.75 does not matter as to the action of the sort function.
    0.75 gives just a bit more random results.
    sure about that? "return -1" does nothing, "return 1" reverses the array.

    how does going 3/4ths of a reversal yield "more random" results than a 50% chance of swap each time (0.5) ?

    if your code worked, this should result in a number around 100:

    for(var i=0, mx=1000;i<mx;i++){
      var r2=r.slice().sort(function() {return 0.75 - Math.random()});
      if(r2[9]===1){ hits+=1; }
    i get 20-something more than half the time, which is not even close to 100, and "0" performs worse than "1".
    or try "if(r2[3]===1){ hits+=1; }", which gives me an avg of about 150, when it should be 100.

    Also of note is that even random()-0.5 does not actually result in a randomized array; early indices are more likely to still be up front when the sort finishes. for a 10 digit array, the odds of slot zero becoming slot 9 are ~4k/1, not 1/10 !
    try testing with 0.5, looking for 1 at slot #9, you see that it's VERY disproportionately scarce compared to looking for 1 at slot #3...

    I suspect that's what you were attempting to compensate for; indeed more reversed sorts "look" more jumbled.

    "0.5" does give better results than 0.75, at least at first...

    The bottom line is that .sort() is not very good at "randomizing" arrays, even if you see it used a lot for that purpose.
    i have to admit, i swallowed that crap without thinking and used it for a while. Until i noticed some of my random pattern generators look obviously non-random, and i dug into code to catch the culprit; [].sort to randomize...

    Carefully avoiding a wiseguy comment about Math.random()'s actual randomness, i will assure that collecting elements at "random()*.length" into a new array is FAR more random.

    if it just has to be "different" instead of "random", [].sort() will almost always re-arrange the array you give it.
    Last edited by rnd me; 09-30-2012 at 06:29 PM.
    Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

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.16888 seconds
  • Memory Usage 2,934KB
  • Queries Executed 15 (?)
More Information
Template Usage (34):
  • (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)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (8)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (8)postbit
  • (8)postbit_onlinestatus
  • (8)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