0

在我的代码中,它使用 pyaudio 来获取用户的音高和音量。它不断在终端中每秒显示数值。 在此处输入图像描述

问题是当我使用 Stringproperty 或 ids 方法在标签中显示它们时,它不显示任何内容。 在此处输入图像描述

但是,在代码中断后,它会显示标签中最后一个音量和音高的数据。 在此处输入图像描述

如何在标签中每秒显示实时数据?

这是我的示例代码.py:

while True:
    
        data = stream.read(1024)
        samples = num.fromstring(data,
            dtype=aubio.float_type)
        pitch = pDetection(samples)[0]
        # Compute the energy (volume) of the
        # current frame.
        volume = num.sum(samples**2)/len(samples)
        # Format the volume output so that at most
        # it has six decimal numbers.
        volume = "{:.6f}".format(volume)
        print(pitch)
        print(volume)
        
        #self.ids.pitchs.text= str(pitch)
        self.ids.volumes.text= volume 
        self.pitchs1 = str(pitch) 
      
            
        if keyboard.is_pressed('1'):  # if key '1' is pressed 
                break  # finishing the[1] loop
        

这是 .kv 文件:

<Genereate>
 GridLayout:
     cols: 1
 GridLayout:
     size: root.width, root.height
     cols:2
     Label:
         id: pitchs
         text: root.pitchs1
         color: 1,0,1,1
    
     Label:
         id: volumes
         text: "Volume"
         color: 1,0,1,1
 Button:
     text: "Submit"
     size_hint: .5, .6
     on_release: root.pitches() 
4

1 回答 1

0

问题是while循环将运行得非常快,用户不会注意到任何变化解决方案是使用kivy时钟模块,如下面创建一个处理计算的方法

def streaming(self, *args):
    data = stream.read(1024)
    samples = num.fromstring(data,
                             dtype=aubio.float_type)
    pitch = pDetection(samples)[0]
    # Compute the energy (volume) of the
    # current frame.
    volume = num.sum(samples ** 2) / len(samples)
    # Format the volume output so that at most
    # it has six decimal numbers.
    volume = "{:.6f}".format(volume)
    print(pitch)
    print(volume)

    # self.ids.pitchs.text= str(pitch)
    self.ids.volumes.text = volume
    self.pitchs1 = str(pitch
            
        

现在你应该使用时钟方法每隔一秒或任何其他时间调用一次


def run_stream(self,):
    schedule=Clock.schedule_interval(streaming, 1)
    # you can stop the steaming like this 
    if keyboard.is_pressed('1'):  # if key '1' is pressed 
        schedule.cancle()

于 2021-08-29T12:57:43.210 回答