Play a sound by calling javascript function

122 views
Skip to first unread message

Rex Allison

unread,
Oct 29, 2016, 4:48:34 PM10/29/16
to Skulpt
I'd like to play a wav file from skulpt. Is there a way to call a javascipt function, with no parameters, from your python code? I've looked at the posting "Call a Generated JS Function" but I think I need a simpler example.

Here is the example sound I have from pressing a button
<audio id="play" src="beep.wav"></audio>
<input type="button" value="PLAY"  onclick="playSound()">


function playSound () {
    document
.getElementById('play').play();
}





Michael Cimino

unread,
Oct 30, 2016, 12:02:36 PM10/30/16
to Skulpt
Hi Rex,

You can create a JavaScript module like this:
Sk.builtinFiles.files['src/lib/playsound/__init__.js'] = (function(){/*
var $builtinmodule = function(name)
{

    var mod = {};

    mod.playSound = new Sk.builtin.func(function(){
        playSound();
        return new Sk.builtin.none;
    })

    return mod;
}*/
}).toString().slice(15,-3);

Then, in the python code, you should be able to run the following:
import playsound
playsound
.playSound()

I hope that helps.
-Michael

Rex Allison

unread,
Oct 30, 2016, 10:17:54 PM10/30/16
to Skulpt
Hi Michael,

Thank you for the response. It took a while to get everything set up and to figure out what I was doing wrong. Now it works.

I added an argument in __init__.js so that it can play multiple sounds with playsound.playSound(arg) in the python code
var $builtinmodule = function(name)
{
   
var mod = {};


    mod
.playSound = new Sk.builtin.func(function(sound_num){
        playSound
(Sk.builtin.asnum$(sound_num));

       
return new Sk.builtin.none;
   
})

   
return mod;
}


Added this to the html:
<audio id="play1" src="blip.wav"></audio>
<audio id="play2" src="crash.wav"></audio>

and this in the script tag
function playSound (snum) {
 
if (snum == 1){
    document
.getElementById('play1').play();
 
}
 
if (snum == 2){
    document
.getElementById('play2').play();
 
}  
}

Thanks again for all the help,
Rex
Reply all
Reply to author
Forward
0 new messages