TypeError:'numpy.ndarray'和'str'的实例之间不支持'>'

时间:2018-06-20 20:41:48

标签: python python-3.x aubio

我希望程序执行的基本操作:

Aubio通过从麦克风输入的内容打印频率(音高)和音量(音量)

我要遍历字典,并根据输出的频率,打印与要输出样本频率的字典中哪个键匹配的颜色

我不断收到此错误:

回溯(最近通话最近): 在“ numpy.ndarray”和“ str”的实例之间不支持TypeError:“>”

任何人都可以帮助我吗?有问题的代码是 for 语句

import aubio
import numpy as num
import pyaudio
import sys

# Some constants for setting the PyAudio and the
# Aubio.
BUFFER_SIZE = 2048
CHANNELS = 1
FORMAT = pyaudio.paFloat32
METHOD = "default"
SAMPLE_RATE = 44100
HOP_SIZE = BUFFER_SIZE//2
PERIOD_SIZE_IN_FRAME = HOP_SIZE
index = 0

def main(args):

    # Initiating PyAudio object.
    pA = pyaudio.PyAudio()
    # Open the microphone stream.
    mic = pA.open(format=FORMAT, channels=CHANNELS,
                  rate=SAMPLE_RATE, input=True,
                  frames_per_buffer=PERIOD_SIZE_IN_FRAME)

    # Initiating Aubio's pitch detection object.
    pDetection = aubio.pitch(METHOD, BUFFER_SIZE,
                             HOP_SIZE, SAMPLE_RATE)
    # Set unit.
    pDetection.set_unit("Hz")
    # Frequency under -40 dB will considered
    # as a silence.
    pDetection.set_silence(-40)

    # Infinite loop!
    while True:

        # Always listening to the microphone.
        data = mic.read(PERIOD_SIZE_IN_FRAME)
        # Convert into number that Aubio understand.
        samples = num.fromstring(data,
                                 dtype=aubio.float_type)
        # Finally get the pitch.
        pitch = pDetection(samples)[0]
        # Compute the energy (volume)
        # of the current frame.
        volume = num.sum(samples**2)/len(samples)
        # Format the volume output so it only
        # displays at most six numbers behind 0.
        volume = "{:6f}".format(volume)

        answer = pitch_detection(samples)

        # Finally print the pitch and the volume.
        print(str(pitch) + " " + str(volume) + (str(answer)))


def pitch_detection(samples):
    colordict = {
        (0.0, 13.99): "Red",
        (14.00, 250.00): "Blue",
    }

    for index, key in enumerate(colordict, start=0):
        if samples > colordict[key][0] and samples < colordict[key][1]:
            return key
        return "Not Found"


if __name__ == "__main__":
    main(sys.argv)

2 个答案:

答案 0 :(得分:1)

samples是一个numpy数组。 colordict[key][0]是一个字符(由于colordict[key]是一个类似"Red"的文本,因此[0]将从字符串"R"中获得第一个字符)

您的比较if samples > colordict[key][0] and samples < colordict[key][1]:正在将numpy数组与一个char进行比较,但失败了。

现在,我不确定您真正想要的是什么。如果您的意思是key[0]key[1](要分别从键中获取每个值),则需要比较一个浮点数,而不是samples(包含多个值-它是一个数组)还是迭代samples进行比较?

答案 1 :(得分:0)

for index, key in enumerate(colordict):
    if pitch > key[0] and pitch < key[1]:
        return colordict[key]

最终修复它。谢谢大家<3