psychopy.org | Reference | Downloads | Github

Can't hear sound but received no errors

PsychoPy version (e.g. 1.84.x): 1.90.1

Hello,
I am new to psychopy and have followed some tutorials to include .wav files in a spreadsheet, and after a few errors like needing to convert sample rates I received no errors and my script ran as planned with the text stimuli. However, I could not hear my sounds! Below are the messages I got after pressing escape and the script. Thank you very much!

When I pressed “escape” after not hearing anything, I received this if that is useful:

27.8915 WARNING Couldn’t measure a consistent frame rate.

Traceback (most recent call last):
File “C:\Program Files\PsychoPy2\lib\site-packages\sounddevice.py”, line 1008, in callback_ptr
return _wrap_callback(callback, data, frames, time, status)
File “C:\Program Files\PsychoPy2\lib\site-packages\sounddevice.py”, line 2773, in _wrap_callback
callback(*args)
File “C:\Program Files\PsychoPy2\lib\site-packages\psychopy\sound\backend_sounddevice.py”, line 194, in callback
toSpk[:len(dat), :] += dat # add to out stream
ValueError: non-broadcastable output operand with shape (128,1) doesn’t match the broadcast shape (128,2)

and below is the script:

#!/usr/bin/env python

-- coding: utf-8 --

“”"
This experiment was created using PsychoPy2 Experiment Builder (v1.90.1),
on December 07, 2018, at 15:31
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
“”"

from future import absolute_import, division
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend ‘np.’
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding

Ensure that relative paths start from the same directory as this script

_thisDir = os.path.dirname(os.path.abspath(file)).decode(sys.getfilesystemencoding())
os.chdir(_thisDir)

Store info about the experiment session

expName = ‘Moser Task Script 12-7-2018’ # from the Builder filename that created this script
expInfo = {u’session’: u’001’, u’participant’: u’’}
dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo[‘date’] = data.getDateStr() # add a simple timestamp
expInfo[‘expName’] = expName

Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc

filename = thisDir + os.sep + u’data/%s%s_%s’ % (expInfo[‘participant’], expName, expInfo[‘date’])

An ExperimentHandler isn’t essential but helps with data saving

thisExp = data.ExperimentHandler(name=expName, version=’’,
extraInfo=expInfo, runtimeInfo=None,
originPath=None,
savePickle=True, saveWideText=True,
dataFileName=filename)

save a log file for detail verbose info

logFile = logging.LogFile(filename+’.log’, level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file

endExpNow = False # flag for ‘escape’ or other condition => quit the exp

Start Code - component code to be run before the window creation

Setup the Window

win = visual.Window(
size=[1920, 1080], fullscr=True, screen=0,
allowGUI=False, allowStencil=False,
monitor=‘testMonitor’, color=[-1.000,-1.000,-1.000], colorSpace=‘rgb’,
blendMode=‘avg’, useFBO=True)

store frame rate of monitor if we can measure it

expInfo[‘frameRate’] = win.getActualFrameRate()
if expInfo[‘frameRate’] != None:
frameDur = 1.0 / round(expInfo[‘frameRate’])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess

Initialize components for Routine “trial1”

trial1Clock = core.Clock()
target = visual.TextStim(win=win, name=‘target’,
text=‘default text’,
font=u’Arial’,
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color=1.0, colorSpace=‘rgb’, opacity=1,
depth=0.0);
Sentences = sound.Sound(‘A’, secs=-1)
Sentences.setVolume(1)

Create some handy timers

globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine

set up handler to look after randomisation of conditions etc

trials = data.TrialHandler(nReps=5, method=‘random’,
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u’conditions.xls’),
seed=None, name=‘trials’)
thisExp.addLoop(trials) # add the loop to the experiment
thisTrial = trials.trialList[0] # so we can initialise stimuli with some values

abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)

if thisTrial != None:
for paramName in thisTrial:
exec(’{} = thisTrial[paramName]’.format(paramName))

for thisTrial in trials:
currentLoop = trials
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
for paramName in thisTrial:
exec(’{} = thisTrial[paramName]’.format(paramName))

# ------Prepare to start Routine "trial1"-------
t = 0
trial1Clock.reset()  # clock
frameN = -1
continueRoutine = True
routineTimer.add(29.000000)
# update component parameters for each repeat
target.setColor([1.000,1.000,1.000], colorSpace='rgb')
target.setText(word)
response = event.BuilderKeyResponse()
Sentences.setSound(sounds, secs=10.0)
# keep track of which components have finished
trial1Components = [target, response, Sentences]
for thisComponent in trial1Components:
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED

# -------Start Routine "trial1"-------
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = trial1Clock.getTime()
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *target* updates
    if t >= 5.0 and target.status == NOT_STARTED:
        # keep track of start time/frame for later
        target.tStart = t
        target.frameNStart = frameN  # exact frame index
        target.setAutoDraw(True)
    frameRemains = 5.0 + 24- win.monitorFramePeriod * 0.75  # most of one frame period left
    if target.status == STARTED and t >= frameRemains:
        target.setAutoDraw(False)
    
    # *response* updates
    if t >= 5.0 and response.status == NOT_STARTED:
        # keep track of start time/frame for later
        response.tStart = t
        response.frameNStart = frameN  # exact frame index
        response.status = STARTED
        # keyboard checking is just starting
        win.callOnFlip(response.clock.reset)  # t=0 on next screen flip
        event.clearEvents(eventType='keyboard')
    frameRemains = 5.0 + 24- win.monitorFramePeriod * 0.75  # most of one frame period left
    if response.status == STARTED and t >= frameRemains:
        response.status = STOPPED
    if response.status == STARTED:
        theseKeys = event.getKeys(keyList=['y', 'n', 'left', 'right', 'space'])
        
        # check for quit:
        if "escape" in theseKeys:
            endExpNow = True
        if len(theseKeys) > 0:  # at least one key was pressed
            response.keys = theseKeys[-1]  # just the last key pressed
            response.rt = response.clock.getTime()
            # a response ends the routine
            continueRoutine = False
    # start/stop Sentences
    if t >= 0.0 and Sentences.status == NOT_STARTED:
        # keep track of start time/frame for later
        Sentences.tStart = t
        Sentences.frameNStart = frameN  # exact frame index
        Sentences.play()  # start the sound (it finishes automatically)
    frameRemains = 0.0 + 10.0- win.monitorFramePeriod * 0.75  # most of one frame period left
    if Sentences.status == STARTED and t >= frameRemains:
        Sentences.stop()  # stop the sound (if longer than duration)
    
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in trial1Components:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished
    
    # check for quit (the Esc key)
    if endExpNow or event.getKeys(keyList=["escape"]):
        core.quit()
    
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "trial1"-------
for thisComponent in trial1Components:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# check responses
if response.keys in ['', [], None]:  # No response was made
    response.keys=None
trials.addData('response.keys',response.keys)
if response.keys != None:  # we had a response
    trials.addData('response.rt', response.rt)
Sentences.stop()  # ensure sound has stopped at end of routine
thisExp.nextEntry()

completed 5 repeats of ‘trials’

these shouldn’t be strictly necessary (should auto-save)

thisExp.saveAsWideText(filename+’.csv’)
thisExp.saveAsPickle(filename)
logging.flush()

make sure everything is closed down

thisExp.abort() # or data files will save again on exit
win.close()
core.quit()

Hi @mjf, the error suggests you are trying to play a mono track into a stereo stream, or vice versa. The latest version of PsychoPy will have an option in Experiment Settings to force stereo, and this should get rid of the error. Alternatively, change the number of channels in your sound file using a sound editor.