www.webdeveloper.com
Results 1 to 8 of 8

Thread: help using javascript using a random file

  1. #1
    Join Date
    Oct 2011
    Location
    Hamilton, Ontario
    Posts
    82

    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) {
    qintup.remove(s1);
    click -= 1;
    }
    else {
    qintup = array["file1","file2", "file3", "file4"];
    click = 3;
    }
    }

    </script>

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

  2. #2
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,391

    Lightbulb

    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).

    Code:
    <!DOCTYPE html>
    <html lang="en">
    <meta charset="utf-8" />
    <head>
    <title> Untitled </title>
    </head>
    
    <body>
    <form onsubmit="return false">
    Click to hear random selection:
    <button onclick="select()"> Play Interval </button>
    </form>
    <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
    }
    </script>
    
    </body>
    </html>

  3. #3
    Join Date
    Oct 2011
    Location
    Hamilton, Ontario
    Posts
    82
    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
    Location
    FL
    Posts
    7,391
    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
    Location
    Hamilton, Ontario
    Posts
    82
    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" />

    script:

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

    what am i missing?

  6. #6
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,391

    Exclamation

    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
    Posts
    79
    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

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

    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

    V

  8. #8
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    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:

    Code:
    r=[0,1,2,3,4,5,6,7,8,9];
    hits=0;
    
    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; }
    }
    
    hits
    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.

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



Recent Articles