Using stimuli and media
***********************


Ready-made files
================

Store each file's URL in the node definition. A file at
"static/instrument_sounds/clarinet.mp3" has the URL
"/static/instrument_sounds/clarinet.mp3". "static_url_for()" converts
a path under "static/" to its URL and raises an error for paths
outside "static/". The "demos/pipelines/similarity" demo lists its
sounds like this:

   def list_stimuli():
       return [
           {
               "name": path.stem,
               "url": static_url_for(path),
           }
           for path in sorted(Path(STIMULUS_DIR).glob(STIMULUS_PATTERN))
       ]

If the files are organized into participant-group and block folders,
"psynet.trial.compile_nodes_from_directory" creates one node per file
and stores its URL in "definition["url"]" by default. Pass "url_key"
to use a different key.

Pass that URL to the page:

   AudioPrompt(self.definition["url"], "How pleasant is this sound?")

"MediaSpec" accepts URLs in the same way, for pages that play several
files, such as the similarity demo's pair of sounds.

The deployment package has a size limit (see How deployment works).
Larger sets of pregenerated files can be hosted elsewhere and linked
by URL, as described in Hosting stimuli on S3, or kept in "data/" and
attached to their nodes as assets:

   Node(definition={"name": path.name}, assets={"stimulus": asset(path)})

PsyNet uploads assets to the experiment's asset storage, skipping
files it has already stored, and the page plays
"self.assets["stimulus"].url". "compile_nodes_from_directory" reads
only "static/", so build these nodes in your own loop (see Managing
assets).


Files generated from code
=========================

Pass a function to "asset()", and attach the result to the node. The
function receives the output "path" to write to, plus any node
definition fields named in its signature. The
"demos/pipelines/tapping" demo builds each metronome stimulus this
way:

   def get_isochronous_stimulus(name, iois, bot_response=None):
       assets = {"stimulus": asset(generate_basic_stimulus, is_folder=True)}

       if bot_response is not None:
           assets["bot_response"] = asset(bot_response)

       return StaticNode(
           definition={
               "stim_name": name,
               "list_iois": iois,
           },
           assets=assets,
       )

   def generate_basic_stimulus(path, stim_name, list_iois):
       stim_prepared, info = create_iso_stim(stim_name, list_iois)
       save_samples_to_file(stim_prepared, path + "/audio.wav", sms_tapping.FS)
       save_json_to_file(info, path + "/info.json")

PsyNet runs "generate_basic_stimulus" at each launch, with "stim_name"
and "list_iois" taken from the node definition. Output identical to a
file already in storage is not uploaded again. Trials read the
generated folder's URL from "self.assets["stimulus"].url" and append
the file name, here "/audio.wav".

"is_folder=True" lets the function write several files into one
folder, here the audio and an "info.json" file used when analyzing the
recording.


Synthesizing stimuli
====================

Synthesized sounds, such as tones, chords or melodies, can be made in
the participant's browser or on your computer before launch.

"JSSynth" synthesizes them in the browser. The node definition holds
the notes, durations and timbre, and the page plays them with Tone.js.
There are no files to generate, store or deploy, and each trial can
use different notes. The sound isn't saved anywhere, though, and it
depends on the browser's audio engine, so it can differ slightly
between browsers and devices. The "experiments/audio" demo plays
chords this way.

Files, generated by a script into "static/" or by a function passed to
"asset()" as above, sound the same for every participant. You can
listen to them, measure them, and include copies in audit evidence.
Files prepared before launch are not included in "psynet export".

For tones, chords and melodies defined by their notes, use "JSSynth":
it is the simplest option and needs no files. Switch to files when
exact acoustic properties such as level, spectrum or timing matter, or
when reviewers should be able to hear the stimuli without running the
experiment. Either way, bots don't hear the sound: "psynet test local"
checks the definitions and saved answers, and with "JSSynth" the only
record of what participants heard is a screen and audio recording of a
browser walk (see Record participant visual evidence).


Participant recordings
======================

Add an "AudioRecordControl" or "VideoRecordControl" to the trial's
page:

   ModularPage(
       "sing",
       AudioPrompt(self.definition["audio_url"], "Sing back the melody."),
       AudioRecordControl(duration=5.0),
       time_estimate=10,
   )

PsyNet stores the recording as an asset of the trial, under the page
label: here, "self.assets["sing"]". A "VideoRecordControl" with
"recording_source="both"" stores two assets, with "_camera" and
"_screen" appended to the label. To analyze a recording on the server,
see After the response.


Where the files end up
======================

"psynet export" downloads assets created during the experiment by
default, such as recordings and stimuli generated while the experiment
runs. Assets prepared before launch are left out. To generate cheap
files that are never stored or exported, use "asset(function,
on_demand=True)". Pass "--assets none" to skip asset files entirely.
See Which assets are included.

See also: Managing assets and Asset in the API reference.
