scratchjr/src/utils/ScratchAudio.js

103 lines
2.7 KiB
JavaScript
Raw Normal View History

2016-01-13 15:54:27 -05:00
import {isAndroid} from './lib';
2016-01-13 18:55:15 -05:00
import Sound from './Sound';
import iOS from '../iPad/iOS';
2016-01-13 15:54:27 -05:00
2016-01-08 14:31:04 -05:00
////////////////////////////////////////////////////
/// Sound Playing
////////////////////////////////////////////////////
let uiSounds = {};
2016-01-13 15:54:27 -05:00
let defaultSounds = ['cut.wav', 'snap.wav', 'copy.wav', 'grab.wav', 'boing.wav', 'tap.wav',
2016-01-08 14:31:04 -05:00
'keydown.wav', 'entertap.wav', 'exittap.wav', 'splash.wav'];
let projectSounds = {};
2016-01-08 14:31:04 -05:00
2016-01-13 15:54:27 -05:00
export default class ScratchAudio {
static get uiSounds () {
return uiSounds;
}
static get projectSounds () {
return projectSounds;
}
2016-01-13 15:54:27 -05:00
static sndFX (name) {
ScratchAudio.sndFXWithVolume(name, 1.0);
2016-01-08 14:31:04 -05:00
}
2016-01-13 15:54:27 -05:00
static sndFXWithVolume (name, volume) {
if (!isAndroid) {
if (!uiSounds[name]) {
return;
2016-01-08 14:31:04 -05:00
}
uiSounds[name].play();
2016-01-13 15:54:27 -05:00
} else {
AndroidInterface.audio_sndfxwithvolume(name, volume);
}
2016-01-08 14:31:04 -05:00
}
2016-01-13 15:54:27 -05:00
static init (prefix) {
if (!prefix) {
prefix = '';
}
if (!isAndroid) {
prefix = 'HTML5/';
2016-01-13 15:54:27 -05:00
}
uiSounds = {};
2016-01-13 15:54:27 -05:00
for (var i = 0; i < defaultSounds.length; i++) {
ScratchAudio.addSound(prefix + 'sounds/', defaultSounds[i], uiSounds);
}
ScratchAudio.addSound(prefix, 'pop.mp3', projectSounds);
2016-01-08 14:31:04 -05:00
}
2016-01-13 15:54:27 -05:00
static addSound (url, snd, dict, fcn) {
var name = snd;
2016-01-13 15:54:27 -05:00
if (!isAndroid) {
var whenDone = function (str) {
if (str != 'error') {
var result = snd.split (',');
dict[snd] = new Sound(result[0], result[1]);
} else {
name = 'error';
2016-01-13 15:54:27 -05:00
}
if (fcn) {
fcn(name);
2016-01-13 15:54:27 -05:00
}
};
iOS.registerSound(url, snd, whenDone);
2016-01-13 15:54:27 -05:00
} else {
// In Android, this is handled outside of JavaScript, so just place a stub here.
dict[snd] = new Sound(url + snd);
2016-01-08 14:31:04 -05:00
if (fcn) {
fcn(snd);
}
}
}
static soundDone (name) {
if (!projectSounds[name]) return;
projectSounds[name].playing = false;
}
2016-01-13 15:54:27 -05:00
static loadProjectSound (md5, fcn) {
if (!md5) {
return;
}
var dir = '';
if (!isAndroid) {
if (md5.indexOf('/') > -1) dir = 'HTML5/';
else if (md5.indexOf('wav') > -1) dir = 'Documents';
2016-01-08 14:31:04 -05:00
}
ScratchAudio.loadFromLocal(dir, md5, fcn);
2016-01-08 14:31:04 -05:00
}
static loadFromLocal (dir, md5, fcn) {
2016-01-13 15:54:27 -05:00
if (projectSounds[md5] != undefined) {
return;
}
ScratchAudio.addSound(dir, md5, projectSounds, fcn);
2016-01-08 14:31:04 -05:00
}
2016-01-13 15:54:27 -05:00
}
2016-01-08 14:31:04 -05:00
window.ScratchAudio = ScratchAudio;