Logo

渕野 裕

Fuchino Yutaka

日本語

Present audio jsPsych 8.3.0

Learn how to preload audio, wait for a participant to start playback, and record a keyboard response. We will trace the sample from top to bottom and explain how each trial fits into the timeline.

jsPsych 8.3.0 · audio

Start audio after a button press

Click to begin, hear a short tone, then listen to a spoken clip

The browser may block audio if a page tries to play it automatically as soon as it loads. In this example, a start screen appears first. Once the participant clicks Start, jsPsych runs two audio trials in sequence.

Start screen
Click Start
→
Tone
Plays for 2 seconds
→
Speech clip
Press a key after playback

The first audio trial plays tone.mp3 for 2,000 milliseconds and accepts no keypress. The second plays speech_joke.mp3; keypresses are ignored while it is playing, and the participant can respond after the clip ends.

Use a local web server such as Live Server to run this example. Browsers may restrict audio loading when the HTML file is opened directly from the file system. Audio behavior can also differ between browsers, so test on the devices participants will use.

Read the script from top to bottom

  1. Load the library, plugins, and stylesheet
    <script src="dist/jspsych.js"></script>
    <script src="dist/plugin-preload.js"></script>
    <script src="dist/plugin-html-button-response.js"></script>
    <script src="dist/plugin-audio-keyboard-response.js"></script>
    <link rel="stylesheet" href="dist/jspsych.css">

    jspsych.js is the library that initializes and runs the experiment. The preload plugin prepares audio files. The HTML button-response plugin creates the start screen. The audio keyboard-response plugin plays a sound and handles keys. The stylesheet controls the basic appearance of jsPsych screens.

    All these files are in the course's dist/ folder. The sample HTML file is next to that folder, so a path like dist/plugin-preload.js means “open the dist folder beside this sample file.” Load the library before its plugins, and load all of them before the experiment script uses them.

  2. Initialize jsPsych and set experiment-wide options
    const jsPsych = initJsPsych({
      default_iti: 1000,
      on_finish: () => {
        jsPsych.data.displayData('csv');
      }
    });

    initJsPsych({...}) creates the jsPsych object and lets you set rules for the whole experiment. The returned object is stored in the jsPsych variable so it can be used to start the timeline and inspect data.

    default_iti means the default inter-trial interval: the short blank pause between one trial and the next. The value is in milliseconds, so 1000 means one second. It applies to trials unless a trial specifies another setting.

    on_finish is a callback function that runs after the complete timeline has finished. The arrow () => begins the function. Here, jsPsych.data.displayData('csv') displays the recorded data in a CSV-style table in the browser. Displaying data is for inspecting this teaching example; it does not download the data or send it to a server.

  3. Preload both audio files
    const preload = {
      type: jsPsychPreload,
      audio: [
        'media/tone.mp3',
        'media/speech_joke.mp3'
      ]
    };

    preload is a variable containing one trial definition. Its type selects the preload plugin. The audio setting is an array, or list, of audio file paths. Each filename is a text string inside quotation marks, and commas separate items in the list.

    Preloading fetches the files before they are needed, which can reduce playback delays. It does not play the sounds. Because the sample HTML file and media/ folder are at the same level, media/tone.mp3 means “open the neighboring media folder and load tone.mp3.” Both paths must point to files that exist.

    The commented line // auto_preload: true is ignored by JavaScript because it starts with //. The preload plugin can also find resources by inspecting the timeline, but this example explicitly lists the two audio files so it is clear what is being loaded.

  4. Show a start button before playing audio
    const start = {
      type: jsPsychHtmlButtonResponse,
      stimulus: '<p>Click the button to play the audio.</p>',
      choices: ['Start']
    };

    This trial uses the HTML button-response plugin. The stimulus is the instruction shown on the screen. The choices array lists the button labels; here there is one button labeled Start.

    The start screen is more than an instruction: the participant's click also satisfies the browser's requirement for a user gesture before audio playback. The trial ends when the participant clicks the button.

  5. Play the first sound for two seconds
    const tone = {
      type: jsPsychAudioKeyboardResponse,
      stimulus: 'media/tone.mp3',
      choices: 'NO_KEYS',
      trial_duration: 2000
    };

    This trial selects the audio keyboard-response plugin and uses tone.mp3 as its stimulus. The stimulus path must match the one listed in the preload trial.

    choices: 'NO_KEYS' tells the plugin not to accept keyboard responses. trial_duration: 2000 sets a limit of 2,000 milliseconds (two seconds). In this example the tone trial ends after that time, regardless of a keypress.

  6. Play the speech clip and wait for a response
    const speech = {
      type: jsPsychAudioKeyboardResponse,
      stimulus: 'media/speech_joke.mp3',
      choices: 'ALL_KEYS',
      response_allowed_while_playing: false,
      prompt: '<p>Press a key after the audio ends.</p>'
    };

    This trial plays speech_joke.mp3. choices: 'ALL_KEYS' allows any keyboard key to count as a response. The prompt is HTML displayed with the audio to tell the participant what to do.

    response_allowed_while_playing: false prevents a keypress from counting while the sound is playing. The plugin begins listening after playback ends. With no trial_duration set, the trial then waits until the participant presses a key; that response ends the trial.

    For comparison, if response_allowed_while_playing were true, a keypress during playback could be recorded. Choose the setting that matches the task you want to measure.

  7. Run the trials in order
    jsPsych.run([preload, start, tone, speech]);

    jsPsych.run(...) starts the experiment. The array lists the trial variables in the order they should run: first preload the files, then wait for a click, play the tone, and finally play the speech clip. The order in this list controls what the participant experiences.

    When the speech trial finishes, there are no more trials. The timeline ends, and the on_finish callback displays the collected data.

Understand the timing between trials

The experiment sets default_iti: 1000, which inserts a one-second interval between trials by default. This pause can give participants a brief break between events and make the transition easier to see. The interval is separate from the duration of a sound trial.

For example, the tone trial has trial_duration: 2000 (two seconds), followed by the default one-second interval before the speech trial begins. The speech trial has no fixed duration because it waits for a response after the audio ends.

What response data is recorded?

The audio keyboard-response plugin records information about each audio trial, including the response key when one is accepted and the response time. A response time is measured in milliseconds. The first tone trial is configured with NO_KEYS, so no key response is collected for that trial.

At the end, jsPsych.data.displayData('csv') displays the data in the browser in CSV format. This example does not save a CSV file to disk. A real research study needs a suitable consent, privacy, and secure data-storage plan.

View the complete shared sample HTML
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>音声提示 / Audio presentation | jsPsych 8.3.0</title>
    <script src="dist/jspsych.js"></script>
    <script src="dist/plugin-preload.js"></script>
    <script src="dist/plugin-html-button-response.js"></script>
    <script src="dist/plugin-audio-keyboard-response.js"></script>
    <link rel="stylesheet" href="dist/jspsych.css">
</head>
<body></body>
<script>
    const jsPsych = initJsPsych({
        default_iti: 1000,
        on_finish: () => {
            jsPsych.data.displayData('csv');
        }
    });

    const preload = {
        type: jsPsychPreload,
        audio: [
            'media/tone.mp3',
            'media/speech_joke.mp3'
        ]
    };

    const start = {
        type: jsPsychHtmlButtonResponse,
        stimulus: '<p>ボタンを押すと音声が流れます。<br>Click the button to play the audio.</p>',
        choices: ['開始 / Start']
    };

    const tone = {
        type: jsPsychAudioKeyboardResponse,
        stimulus: 'media/tone.mp3',
        choices: 'NO_KEYS',
        trial_duration: 2000
    };

    const speech = {
        type: jsPsychAudioKeyboardResponse,
        stimulus: 'media/speech_joke.mp3',
        choices: 'ALL_KEYS',
        response_allowed_while_playing: false,
        prompt: '<p>音声終了後にキーを押してください。<br>Press a key after the audio ends.</p>'
    };

    jsPsych.run([preload, start, tone, speech]);
</script>
</html>

Back to the course contents ↑