Search code examples
matlabaudiopsychtoolbox

Creating alarm sound in psychtoolbox matlab


I am trying to create an experiment on psychtoolbox and one part of it involves sounding an alarm when the participant fail to respond.

I tried using the beep provided but it does not sound like an alarm at all. Is there any way to achieve that without having to download a external sound?

I have no knowledge of sound or sound waves so please help!


Solution

  • The following code will load a .wav file, and play it through the Psychtoolbox audio system. This allows you to have a timestamp of sound onset, and allows greater control than using sound() or beep. You could alternatively generate a tone using MATLAB itself (it is easy to generate a sine wave of a particular frequency) and use that instead of the .wav data.

    %% this block only needs to be performed once, at the start of the experiment
    
    % initialize the Psychtoolbox audio system in low latency mode
    InitializePsychSound(1);
    
    % load in a waveform for the warning
    [waveform,Fs] = audioread('alarm.wav');
    numChannels = size(waveform, 2);
    
    % open the first audio device in low-latency, stereo mode
    % if you have more than one device attached, you will need to specify the
    % appropriate deviceid
    pahandle = PsychPortAudio('Open', 2, [], 1, Fs, numChannels);
    
    
    %% during the experiment, when you want to play the alarm
    PsychPortAudio('FillBuffer', pahandle, waveform' );
    startTime = PsychPortAudio('Start', pahandle, 1);
    
    %% at the conclusion of the experiment
    PsychPortAudio('Close');
    

    If you'd like to generate your own sound, take a look at the Psychtoolbox function 'MakeBeep', and substitute that in, instead of the waveform, for example, a 1000 Hz tone, lasting 250ms, at a 44.1k sampling rate:

    % generate a beep
    beepWaveform = MakeBeep(1000,.250,44100);
    
    % make stereo
    beepWaveform = repmat(beepWaveform, 2, 1);
    
    % fill buffer, play
    PsychPortAudio('FillBuffer', pahandle, beepWaveform );
    startTime = PsychPortAudio('Start', pahandle, 1);