danigb / soundfont-player

Quick soundfont loader and player for browser
MIT License
455 stars 59 forks source link

instrument.play() is not a function? #34

Closed laniel closed 8 years ago

laniel commented 8 years ago

Running the following code seems to be returning a "Uncaught TypeError: marimba.play is not a function".

var marimba = soundfont.instrument(new AudioContext(), 'marimba'); marimba.play('C4');

Seems as though every time I try to set a variable to an instrument I cannot play. Any suggestions?

danigb commented 8 years ago

Hi @laniel,

The instrument function returns a Promise. So instead of:

soundfont.instrument(ac, 'marimba').play()

you should write:

soundfont.instrument(ac, 'marimba').then(function (marimba) {
  marimba.play('C4')
})

Hope it helps.

laniel commented 8 years ago

Thanks for the response. I saw those examples, but I would like to load an instrument on loading the page and then play a note based on future events without the need to reload the instrument each time. Any ways of doing this?

danigb commented 8 years ago

Yes. You can call then several times over the same promise to get the instrument without reloading:

var marimba = load(ac, 'marimba');
marimba.then(function (inst) {
  inst.play('C4')
})
// later...
marimba.then(function(inst) {
  // you get the same inst instance than before
  inst.play('d4')
})

Another (less clean) option is to setup a global variable and initialize when the promise resolves. Then play the note if the global variable is initialized.

Hope it helps

danigb commented 8 years ago

I understand this is working for you. Please feel free to reopen if not. Regards, Dani

laniel commented 8 years ago

var marimba = load(ac, 'marimba'); marimba.then(function (inst) { inst.play('C4') }) // later... marimba.then(function(inst) { // you get the same inst instance than before inst.play('d4') })

This is still giving me "inst.play is not a function".