This commit is contained in:
ericrius1 2016-02-05 17:13:29 -08:00
parent 1c54de6f57
commit 4c33c6e171
5 changed files with 182 additions and 401 deletions

View file

@ -5,126 +5,203 @@
// Created by Eric Levin 2/1/2016
// Copyright 2016 High Fidelity, Inc.
// This AC script constantly searches for entities with a special userData field that specifies audio settings, and then
// injects the sound with the specified URL with other specified settings (playback volume) or playback at interval, or random interval
// This AC script searches for special sound entities nearby avatars and plays those sounds based off information specified in the entity's
// user data field ( see acAudioSearchAndCompatibilityEntitySpawner.js for an example)
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
Script.include("https://rawgit.com/highfidelity/hifi/master/examples/libraries/utils.js");
var SOUND_DATA_KEY = "soundKey";
var MESSAGE_CHANNEL = "Hifi-Sound-Entity";
// Map of all sound entities in domain- key is entity id, value is sound data
var soundEntityMap = {};
// Map of sound urls so a sound that's already been downloaded from one entity is not re-downloaded if
// another entity with same sound url is discovered
var soundUrls = {};
var QUERY_RADIUS = 50;
EntityViewer.setPosition({
x: 0,
y: 0,
z: 0
});
EntityViewer.setKeyholeRadius(60000);
EntityViewer.setKeyholeRadius(QUERY_RADIUS);
Entities.setPacketsPerSecond(6000);
Agent.isAvatar = true;
var DEFAULT_SOUND_DATA = {
volume: 0.5,
loop: false,
interval: -1, // An interval of -1 means this sound only plays once (if it's non-looping) (In seconds)
intervalSpread: 0 // amount of randomness to add to the interval
};
var MIN_INTERVAL = 0.2;
EntityViewer.queryOctree();
var MIN_PLAY_INTERVAL = 0.2;
function messageReceived(channel, message, sender) {
print("EBL MESSAGE RECIEVED");
var entityID = JSON.parse(message).id;
if (soundEntityMap[entityID]) {
// We already have this entity in our sound map, so don't re-add
return;
}
var UPDATE_TIME = 100;
var EXPIRATION_TIME = 20000;
EntityViewer.queryOctree();
Script.setTimeout(function() {
handleIncomingEntity(entityID);
}, 2000);
var soundEntityMap = {};
var soundUrls = {};
}
var avatarPositions = [];
function handleIncomingEntity(entityID) {
var soundData = getEntityCustomData(SOUND_DATA_KEY, entityID);
print("SOUND DATA " + JSON.stringify(soundData));
if (soundData && soundData.url) {
var soundProperties = {
url: soundData.url,
volume: soundData.volume || DEFAULT_SOUND_DATA.volume,
loop: soundData.loop || DEFAULT_SOUND_DATA.loop,
interval: soundData.interval || DEFAULT_SOUND_DATA.interval,
intervalSpread: soundData.intervalSpread || DEFAULT_SOUND_DATA.intervalSpread,
readyToPlay: true,
position: Entities.getEntityProperties(entityID, "position").position,
timeSinceLastPlay: 0
};
if (soundProperties.interval !== -1) {
soundProperties.currentInterval = soundProperties.interval + randFloat(-soundProperties.intervalSpread, soundProperties.intervalSpread);
soundProperties.currentInterval = Math.max(MIN_INTERVAL, soundProperties.currentInterval);
}
if (!soundUrls[soundData.url]) {
// We need to download sound before we add it to our map
var sound = SoundCache.getSound(soundData.url);
soundUrls[soundData.url] = sound;
// Only add it to map once it's downloaded
sound.ready.connect(function() {
soundProperties.sound = sound;
soundEntityMap[entityID] = soundProperties;
});
} else {
// We already have sound downloaded, so just add it to map right away
soundProperties.sound = soundUrls[soundData.url];
soundEntityMap[entityID] = soundProperties;
}
}
}
function update(deltaTime) {
// Go through each sound and play it if it needs to be played
for (var potentialEntity in soundEntityMap) {
if (!soundEntityMap.hasOwnProperty(potentialEntity)) {
// The current property is not a direct propert of soundEntityMap so ignore it
function update() {
var avatars = AvatarList.getAvatarIdentifiers();
for (var i = 0; i < avatars.length; i++) {
var avatar = AvatarList.getAvatar(avatars[i]);
var avatarPosition = avatar.position;
if (!avatarPosition) {
continue;
}
var entity = potentialEntity;
var soundProperties = soundEntityMap[entity];
if (soundProperties.readyToPlay) {
var newPosition = Entities.getEntityProperties(entity, "position").position
print("EBL SHOULD BE PLAYING SOUND!")
Audio.playSound(soundProperties.sound, {
volume: soundProperties.volume,
position: newPosition,
loop: soundProperties.loop
});
soundProperties.readyToPlay = false;
} else if (soundProperties.loop === false && soundProperties.interval !== -1) {
// We need to check all of our entities that are not looping but have an interval associated with them
// to see if it's time for them to play again
soundProperties.timeSinceLastPlay += deltaTime;
if (soundProperties.timeSinceLastPlay > soundProperties.currentInterval) {
soundProperties.readyToPlay = true;
soundProperties.timeSinceLastPlay = 0;
// Now lets get our next current interval
soundProperties.currentInterval = soundProperties.interval + randFloat(-soundProperties.intervalSpread, soundProperties.intervalSpread);
soundProperties.currentInterval = Math.max(MIN_INTERVAL, soundProperties.currentInterval);
EntityViewer.setPosition(avatarPosition);
EntityViewer.queryOctree();
avatarPositions.push(avatarPosition);
}
Script.setTimeout(function() {
avatarPositions.forEach(function(avatarPosition) {
var entities = Entities.findEntities(avatarPosition, QUERY_RADIUS);
handleFoundSoundEntities(entities);
});
//Now wipe list for next query;
avatarPositions = [];
}, 1000);
handleActiveSoundEntities();
}
function handleActiveSoundEntities() {
// Go through all our sound entities, if they have passed expiration time, remove them from map
for (var potentialSoundEntity in soundEntityMap) {
if (!soundEntityMap.hasOwnProperty(potentialSoundEntity)) {
// The current property is not a direct property of soundEntityMap so ignore it
continue;
}
var soundEntity = potentialSoundEntity;
var soundProperties = soundEntityMap[soundEntity];
soundProperties.timeWithoutAvatarInRange += UPDATE_TIME;
if (soundProperties.timeWithoutAvatarInRange > EXPIRATION_TIME && soundProperties.soundInjector) {
// An avatar hasn't been within range of this sound entity recently, so remove it from map
soundProperties.soundInjector.stop();
delete soundEntityMap[soundEntity];
} else if (soundProperties.isDownloaded) {
// If this sound hasn't expired yet, we want to potentially play it!
if (soundProperties.readyToPlay) {
var newPosition = Entities.getEntityProperties(soundEntity, "position").position;
if (!soundProperties.soundInjector) {
soundProperties.soundInjector = Audio.playSound(soundProperties.sound, {
volume: soundProperties.volume,
position: newPosition,
loop: soundProperties.loop
});
} else {
soundProperties.soundInjector.restart();
}
soundProperties.readyToPlay = false;
} else if (soundProperties.sound && soundProperties.loop === false && soundProperties.interval !== -1) {
// We need to check all of our entities that are not looping but have an interval associated with them
// to see if it's time for them to play again
soundProperties.timeSinceLastPlay += UPDATE_TIME;
if (soundProperties.timeSinceLastPlay > soundProperties.currentInterval) {
soundProperties.readyToPlay = true;
soundProperties.timeSinceLastPlay = 0;
// Now let's get our new current interval
soundProperties.currentInterval = soundProperties.interval + randFloat(-soundProperties.intervalSpread, soundProperties.intervalSpread);
soundProperties.currentInterval = Math.max(MIN_PLAY_INTERVAL, soundProperties.currentInterval);
}
}
}
}
}
Script.update.connect(update);
Messages.subscribe(MESSAGE_CHANNEL);
Messages.messageReceived.connect(messageReceived);
function handleFoundSoundEntities(entities) {
entities.forEach(function(entity) {
var soundData = getEntityCustomData(SOUND_DATA_KEY, entity);
if (soundData && soundData.url) {
//check sound entities list- if it's not in, add it
if (!soundEntityMap[entity]) {
print("NEW SOUND!")
var soundProperties = {
url: soundData.url,
volume: soundData.volume || DEFAULT_SOUND_DATA.volume,
loop: soundData.loop || DEFAULT_SOUND_DATA.loop,
interval: soundData.interval || DEFAULT_SOUND_DATA.interval,
intervalSpread: soundData.intervalSpread || DEFAULT_SOUND_DATA.intervalSpread,
readyToPlay: false,
position: Entities.getEntityProperties(entity, "position").position,
timeSinceLastPlay: 0,
timeWithoutAvatarInRange: 0,
isDownloaded: false
};
if (soundProperties.interval !== -1) {
soundProperties.currentInterval = soundProperties.interval + randFloat(-soundProperties.intervalSpread, soundProperties.intervalSpread);
soundProperties.currentInterval = Math.max(MIN_PLAY_INTERVAL, soundProperties.currentInterval);
}
soundEntityMap[entity] = soundProperties;
if (!soundUrls[soundData.url]) {
// We need to download sound before we add it to our map
var sound = SoundCache.getSound(soundData.url);
// Only add it to map once it's downloaded
soundUrls[soundData.url] = sound;
sound.ready.connect(function() {
soundProperties.sound = sound;
soundProperties.readyToPlay = true;
soundProperties.isDownloaded = true;
soundEntityMap[entity] = soundProperties;
});
} else {
// We already have sound downloaded, so just add it to map right away
soundProperties.sound = soundUrls[soundData.url];
soundProperties.readyToPlay = true;
soundProperties.isDownloaded = true;
soundEntityMap[entity] = soundProperties;
}
} else {
//If this sound is in our map already, we want to reset timeWithoutAvatarInRange
// Also we want to check to see if the entity has been updated with new sound data- if so we want to update!
soundEntityMap[entity].timeWithoutAvatarInRange = 0;
checkForSoundPropertyChanges(soundEntityMap[entity], soundData);
}
}
});
}
function checkForSoundPropertyChanges(currentProps, newProps) {
var needsNewInjector = false;
if (currentProps.interval !== newProps.interval && !currentProps.loop) {
// interval only applies to non looping sounds
currentProps.interval = newProps.interval;
currentProps.currentInterval = currentProps.interval + randFloat(-currentProps.intervalSpread, currentProps.intervalSpread);
currentProps.currentInterval = Math.max(MIN_PLAY_INTERVAL, currentProps.currentInterval);
currentProps.readyToPlay = true;
}
if (currentProps.intervalSpread !== currentProps.intervalSpread) {
currentProps.currentInterval = currentProps.interval + randFloat(-currentProps.intervalSpread, currentProps.intervalSpread);
currentProps.currentInterval = Math.max(MIN_PLAY_INTERVAL, currentProps.currentInterval);
}
if (currentProps.volume !== newProps.volume) {
currentProps.volume = newProps.volume;
needsNewInjector = true;
}
if (currentProps.url !== newProps.url) {
currentProps.url = newProps.url;
currentProps.sound = null;
if (!soundUrls[currentProps.url]) {
var sound = SoundCache.getSound(currentProps.url);
currentProps.isDownloaded = false;
sound.ready.connect(function() {
currentProps.sound = sound;
currentProps.isDownloaded = true;
});
} else {
currentProps.sound = sound;
}
needsNewInjector = true;
}
if (needsNewInjector) {
// If we were looping we need to stop that so new changes are applied
currentProps.soundInjector.stop();
currentProps.soundInjector = null;
currentProps.readyToPlay = true;
}
}
Script.setInterval(update, UPDATE_TIME);

View file

@ -1,202 +0,0 @@
//
Script.include("https://rawgit.com/highfidelity/hifi/master/examples/libraries/utils.js");
var SOUND_DATA_KEY = "soundKey";
var QUERY_RADIUS = 5;
EntityViewer.setKeyholeRadius(QUERY_RADIUS);
Entities.setPacketsPerSecond(6000);
Agent.isAvatar = true;
var DEFAULT_SOUND_DATA = {
volume: 0.5,
loop: false,
interval: -1, // An interval of -1 means this sound only plays once (if it's non-looping) (In seconds)
intervalSpread: 0 // amount of randomness to add to the interval
};
var MIN_PLAY_INTERVAL = 0.2;
var UPDATE_TIME = 100;
var EXPIRATION_TIME = 7000;
var soundEntityMap = {};
var soundUrls = {};
var avatarPositions = [];
print("EBL STARTING SCRIPT");
function update() {
var avatars = AvatarList.getAvatarIdentifiers();
for (var i = 0; i < avatars.length; i++) {
var avatar = AvatarList.getAvatar(avatars[i]);
var avatarPosition = avatar.position;
if (!avatarPosition) {
print("EBL This avatars been DELETED *******! Don't add it to list");
continue;
}
EntityViewer.setPosition(avatarPosition);
EntityViewer.queryOctree();
avatarPositions.push(avatarPosition);
}
Script.setTimeout(function() {
avatarPositions.forEach(function(avatarPosition) {
var entities = Entities.findEntities(avatarPosition, QUERY_RADIUS);
handleFoundSoundEntities(entities);
});
//Now wipe list for next query;
avatarPositions = [];
}, 1000);
handleActiveSoundEntities();
}
function handleActiveSoundEntities() {
// Go through all our sound entities, if they have passed expiration time, remove them from map
for (var potentialSoundEntity in soundEntityMap) {
if (!soundEntityMap.hasOwnProperty(potentialSoundEntity)) {
// The current property is not a direct property of soundEntityMap so ignore it
continue;
}
var soundEntity = potentialSoundEntity;
var soundProperties = soundEntityMap[soundEntity];
soundProperties.timeWithoutAvatarInRange += UPDATE_TIME;
if (soundProperties.timeWithoutAvatarInRange > EXPIRATION_TIME && soundProperties.soundInjector) {
print("THIS ENTITY IS GONE OR NO AVATARS ARE IN RANGE!")
// An avatar hasn't been within range of this sound entity recently, so remove it from map
soundProperties.soundInjector.stop();
delete soundEntityMap[soundEntity];
} else if (soundProperties.isDownloaded) {
// If this sound hasn't expired yet, we want to potentially play it!
if (soundProperties.readyToPlay) {
var newPosition = Entities.getEntityProperties(soundEntity, "position").position;
if (!soundProperties.soundInjector) {
print("PLAY first injector!!!")
soundProperties.soundInjector = Audio.playSound(soundProperties.sound, {
volume: soundProperties.volume,
position: newPosition,
loop: soundProperties.loop
});
} else {
print("PLAY!!")
soundProperties.soundInjector.restart();
}
soundProperties.readyToPlay = false;
} else if (soundProperties.sound && soundProperties.loop === false && soundProperties.interval !== -1) {
// We need to check all of our entities that are not looping but have an interval associated with them
// to see if it's time for them to play again
soundProperties.timeSinceLastPlay += UPDATE_TIME;
if (soundProperties.timeSinceLastPlay > soundProperties.currentInterval) {
soundProperties.readyToPlay = true;
soundProperties.timeSinceLastPlay = 0;
// Now let's get our new current interval
soundProperties.currentInterval = soundProperties.interval + randFloat(-soundProperties.intervalSpread, soundProperties.intervalSpread);
soundProperties.currentInterval = Math.max(MIN_PLAY_INTERVAL, soundProperties.currentInterval);
print("CURRENT INTERVAL " + soundProperties.currentInterval)
}
}
}
}
}
function handleFoundSoundEntities(entities) {
entities.forEach(function(entity) {
var soundData = getEntityCustomData(SOUND_DATA_KEY, entity);
if (soundData && soundData.url) {
//check sound entities list- if it's not in, add it
if (!soundEntityMap[entity]) {
print("NEW SOUND!")
var soundProperties = {
url: soundData.url,
volume: soundData.volume || DEFAULT_SOUND_DATA.volume,
loop: soundData.loop || DEFAULT_SOUND_DATA.loop,
interval: soundData.interval || DEFAULT_SOUND_DATA.interval,
intervalSpread: soundData.intervalSpread || DEFAULT_SOUND_DATA.intervalSpread,
readyToPlay: false,
position: Entities.getEntityProperties(entity, "position").position,
timeSinceLastPlay: 0,
timeWithoutAvatarInRange: 0,
isDownloaded: false
};
if (soundProperties.interval !== -1) {
soundProperties.currentInterval = soundProperties.interval + randFloat(-soundProperties.intervalSpread, soundProperties.intervalSpread);
soundProperties.currentInterval = Math.max(MIN_PLAY_INTERVAL, soundProperties.currentInterval);
}
soundEntityMap[entity] = soundProperties;
if (!soundUrls[soundData.url]) {
// We need to download sound before we add it to our map
var sound = SoundCache.getSound(soundData.url);
// Only add it to map once it's downloaded
soundUrls[soundData.url] = sound;
sound.ready.connect(function() {
soundProperties.sound = sound;
soundProperties.readyToPlay = true;
soundProperties.isDownloaded = true;
soundEntityMap[entity] = soundProperties;
});
} else {
// We already have sound downloaded, so just add it to map right away
soundProperties.sound = soundUrls[soundData.url];
soundProperties.readyToPlay = true;
soundProperties.isDownloaded = true;
soundEntityMap[entity] = soundProperties;
}
} else {
//If this sound is in our map already, we want to reset timeWithoutAvatarInRange
// Also we want to check to see if the entity has been updated with new sound data- if so we want to update!
soundEntityMap[entity].timeWithoutAvatarInRange = 0;
checkForSoundPropertyChanges(soundEntityMap[entity], soundData);
}
}
});
}
function checkForSoundPropertyChanges(currentProps, newProps) {
var needsNewInjector = false;
if (currentProps.interval !== newProps.interval && !currentProps.loop) {
// interval only applies to non looping sounds
currentProps.interval = newProps.interval;
currentProps.currentInterval = currentProps.interval + randFloat(-currentProps.intervalSpread, currentProps.intervalSpread);
currentProps.currentInterval = Math.max(MIN_PLAY_INTERVAL, currentProps.currentInterval);
currentProps.readyToPlay = true;
}
if (currentProps.intervalSpread !== currentProps.intervalSpread) {
currentProps.currentInterval = currentProps.interval + randFloat(-currentProps.intervalSpread, currentProps.intervalSpread);
currentProps.currentInterval = Math.max(MIN_PLAY_INTERVAL, currentProps.currentInterval);
}
if (currentProps.volume !== newProps.volume) {
currentProps.volume = newProps.volume;
needsNewInjector = true;
}
if (currentProps.url !== newProps.url) {
currentProps.url = newProps.url;
currentProps.sound = null;
if (!soundUrls[currentProps.url]) {
var sound = SoundCache.getSound(currentProps.url);
currentProps.isDownloaded = false;
sound.ready.connect(function() {
currentProps.sound = sound;
currentProps.isDownloaded = true;
});
} else {
currentProps.sound = sound;
}
needsNewInjector = true;
}
if (needsNewInjector) {
// If we were looping we need to stop that so new changes are applied
currentProps.soundInjector.stop();
currentProps.soundInjector = null;
currentProps.readyToPlay = true;
}
}
Script.setInterval(update, UPDATE_TIME);

View file

@ -14,27 +14,26 @@
//
Script.include("../../libraries/utils.js");
var orientation = Camera.getOrientation();
orientation = Quat.safeEulerAngles(orientation);
orientation.x = 0;
orientation = Quat.fromVec3Degrees(orientation);
var center = Vec3.sum(MyAvatar.position, Vec3.multiply(3, Quat.getFront(orientation)));
// http://hifi-public.s3.amazonaws.com/ryan/demo/0619_Fireplace__Tree_B.L.wav
var SOUND_DATA_KEY = "soundKey";
var MESSAGE_CHANNEL = "Hifi-Sound-Entity";
var SCRIPT_URL = Script.resolvePath("soundEntityScript.js?v1" + Math.random());
var userData = {
soundKey: {
url: "https://s3-us-west-1.amazonaws.com/hifi-content/eric/Sounds/dove.wav",
url: "https://s3-us-west-1.amazonaws.com/hifi-content/eric/Sounds/dove2.wav",
volume: 0.3,
loop: false,
interval: 4,
intervalSpread: 2
interval: 2000,
intervalSpread: 1000
}
}
var entityProps = {
type: "Box",
position: {
x: Math.random(),
y: 0,
z: 0
},
position: center,
color: {
red: 200,
green: 10,
@ -45,8 +44,7 @@ var entityProps = {
y: 0.1,
z: 0.1
},
userData: JSON.stringify(userData),
script: SCRIPT_URL
userData: JSON.stringify(userData)
}
var soundEntity = Entities.addEntity(entityProps);

View file

@ -1,56 +0,0 @@
//
// acAudioSearchCompatibleEntitySpawner.js
// audio/acAudioSearching
//
// Created by Eric Levin 2/2/2016
// Copyright 2016 High Fidelity, Inc.
// This is a client script which spawns entities with a field in userData compatible with the AcAudioSearchAndInject script
// These entities specify data about the sound they want to play, such as url, volume, and whether to loop or not
// The position of the entity determines the position from which the sound plays from
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
Script.include("../../libraries/utils.js");
// http://hifi-public.s3.amazonaws.com/ryan/demo/0619_Fireplace__Tree_B.L.wav
var SOUND_DATA_KEY = "soundKey";
var userData = {
soundKey: {
url: "https://s3-us-west-1.amazonaws.com/hifi-content/eric/Sounds/dove2.wav",
volume: 0.3,
loop: false,
interval: 2000,
intervalSpread: 1000
}
}
var entityProps = {
type: "Box",
position: {
x: Math.random(),
y: 0,
z: 0
},
color: {
red: 200,
green: 10,
blue: 200
},
dimensions: {
x: 0.1,
y: 0.1,
z: 0.1
},
userData: JSON.stringify(userData)
}
var soundEntity = Entities.addEntity(entityProps);
function cleanup() {
Entities.deleteEntity(soundEntity);
}
Script.scriptEnding.connect(cleanup);

View file

@ -1,36 +0,0 @@
// soundEntityScript.js
//
// Script Type: Entity
// Created by Eric Levin on 2/2/16.
// Copyright 2016 High Fidelity, Inc.
//
// This entity script sends a message meant for a running AC script on its preload
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
(function() {
Script.include("../../libraries/utils.js");
var _this;
// this is the "constructor" for the entity as a JS object we don't do much here
var SoundEntity = function() {
_this = this;
this.MESSAGE_CHANNEL = "Hifi-Sound-Entity";
};
SoundEntity.prototype = {
preload: function(entityID) {
this.entityID = entityID;
Script.setTimeout(function() {
var soundData = getEntityCustomData("soundKey", _this.entityID);
// Just a hack for now until bug https://app.asana.com/0/26225263936266/86767805352289 is fixed
print("EBL SEND MESSAGE");
Messages.sendMessage(_this.MESSAGE_CHANNEL, JSON.stringify({
id: _this.entityID
}));
}, 2000);
},
};
// entity scripts always need to return a newly constructed object of our type
return new SoundEntity();
});