我正在尝试将sound.Sound()
函数应用于循环中的numpy数组。具体来说,我想在下面循环执行。 numpy数组是a_wave到d_wave。
stim_a = sound.Sound(a_wave)
stim_b = sound.Sound(b_wave)
stim_c = sound.Sound(c_wave)
stim_d = sound.Sound(d_wave)
我已经尝试过下面的循环。
import sys
this = sys.modules[__name__]
import string
letters = list(string.ascii_lowercase)
a_d = letters[:4]
for x in range(len(a_d)):
setattr(this, 'stim_%s' % a_d[x], sound.Sound('%s_wave' % a_d[x]))
但是我得到以下错误:
File "C:\Program Files (x86)\PsychoPy2\lib\site-packages\psychopy-1.83.01-py2.7.egg\psychopy\sound.py", line 389, in __init__
self.setSound(value=value, secs=secs, octave=octave, hamming=hamming)
File "C:\Program Files (x86)\PsychoPy2\lib\site-packages\psychopy-1.83.01-py2.7.egg\psychopy\sound.py", line 146, in setSound
raise ValueError, "setSound: could not find a sound file named " + value
ValueError: setSound: could not find a sound file named a_wave
如果能就此事获得一些建议,我将不胜感激。我在下面插入整个代码以供参考。
from __future__ import division
from psychopy import sound
import sys
this = sys.modules[__name__]
import numpy as np
import string
#generate string lists
letters = list(string.ascii_lowercase)
a_d = letters[:4]
sampling_rate = 44100 #in Hz
target_fq = 200
long_dur = 0.150
short_dur = 0.066
short_blank = 0.066
long_blank = 0.150
double_blank = 0.233
#short
short_index = np.array(range(int(round(short_dur / (1/float(sampling_rate)))-1)))
short_wave = np.sin(2*np.pi*target_fq*(short_index/float(sampling_rate)))
short_blank_wave = np.zeros(short_blank*sampling_rate) #Small fudge factor to bring total stim length to 4410
#long
long_index = np.array(range(int(round(long_dur / (1/float(sampling_rate)))-1)))
long_wave = np.sin(2*np.pi*target_fq*(long_index/float(sampling_rate)))
long_blank_wave = np.zeros(long_blank*sampling_rate)
#double blank
double_blank_wave = np.zeros(double_blank*sampling_rate)
#numpy arrays
a_wave = np.concatenate((long_wave, short_blank_wave, long_wave), axis=0)
b_wave = np.concatenate((short_wave, long_blank_wave, long_wave), axis=0)
c_wave = np.concatenate((long_wave, long_blank_wave, short_wave), axis=0)
d_wave = np.concatenate((short_wave, double_blank_wave, short_wave), axis=0)
for x in range(len(a_d)):
setattr(this, 'stim_%s' % a_d[x], sound.Sound('%s_wave' % a_d[x]))
答案 0 :(得分:1)
您(以非常复杂的方式)只是构造字符串(例如'a_wave'
)以传递给声音对象。声音对象自然会将它们解释为要打开的文件名,这会失败。也就是说,请注意,字符串'a_wave'
与您要引用的numpy数组对象a_wave
不对应。
您可以简单地执行以下操作:
sound_stim = sound.Sound()
for sound_array in (a_wave, b_wave, c_wave, d_wave):
for entry in sound_array:
sound_stim.setSound(entry)
sound_stim.play()
# probably need some sort of delay loop here, as
# playing doesn't block execution.
但是,由于您没有明确表达要达到的目标,我只是在这里猜测。请注意,数组a_wave
等根本不需要是numpy数组,它们可以只是Python列表,这将简化其构造。例如
a_wave = [long_wave, short_blank_wave, long_wave]
通常,您过度设计了代码。保持简单和Pythonic。