2017-08-10 21 views
0

我是新來的,希望我的問題就在這裏。 我想編程一個GUI,我可以從麥克風錄製一些聲音並實時繪製它,以查看聲音的左右聲道。Matplotlib-PyQt5中的圖表在運行時沒有更新

我使用PyQt 5作爲我的GUI和Matplotlib-FigureCanvas作圖。 流媒體工作正常,但是Plot僅在錄製停止後顯示,並且在錄製期間不會更新,就像它應該一樣。 在調試模式下,我可以在每次更新時看到圖表,但是當我運行代碼時,GUI會凍結,直到錄製完成。 就是這樣,因爲繪圖太慢了? 我嘗試了使用動畫或線程的不同方法,但到目前爲止沒有任何工作。

我想最終有一個實時更新的陰謀,我該怎麼做到這一點?還有更長的錄音?

我希望有人能幫助我,在此先感謝!

這裏是我的代碼,在那裏我記錄並繪製出部分:

import sys 
from PyQt5 import QtGui, QtWidgets, QtCore 
import numpy as np 
import time 
import pyaudio 
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas 
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar 
from matplotlib.figure import Figure 
import matplotlib.gridspec as gridspec 
import matplotlib.animation as animation 


class Window(QtWidgets.QMainWindow): 

    def __init__(self): # sort of template for rest of GUI, is always there, menubar/ mainmenu eg. 
     super(Window, self).__init__() 
     self.setGeometry(50, 50, 1500, 900) 
     self.setWindowTitle("PyQt Tutorial!") 

     self.centralwidget = QtWidgets.QWidget(self) 
     self.centralwidget.setObjectName("centralwidget") 

     self.channels = 2 
     self.fs = 44100 # samplerate 
     self.Chunks = 1024 

     self.tapeLength = 2 # seconds 
     self.tape = np.empty(self.fs * self.tapeLength) * np.nan # tapes where recorded audio is stored 
     self.taper = np.empty(self.fs * self.tapeLength) * np.nan 
     self.tapel = np.empty(self.fs * self.tapeLength) * np.nan 

     self.home() 

    def home(self): 
     btn = QtWidgets.QPushButton("Stream and Plot", self) # Button to start streaming 
     btn.clicked.connect(self.plot) 
     btn.resize(btn.sizeHint()) 
     btn.move(100, 100) 

     self.scrollArea = QtWidgets.QScrollArea(self) 
     self.scrollArea.move(75, 400) 
     self.scrollArea.resize(600, 300) 
     self.scrollArea.setWidgetResizable(False) 

     self.scrollArea2 = QtWidgets.QScrollArea(self) 
     self.scrollArea2.move(775, 400) 
     self.scrollArea2.resize(600, 300) 
     self.scrollArea2.setWidgetResizable(False) 
     self.scrollArea.horizontalScrollBar().valueChanged.connect(self.scrollArea2.horizontalScrollBar().setValue) 
     self.scrollArea2.horizontalScrollBar().valueChanged.connect(self.scrollArea.horizontalScrollBar().setValue) 

     self.figure = Figure((15, 2.8), dpi=100) # figure instance (to plot on) F(width, height, ...) 
     self.canvas = FigureCanvas(self.figure) 
     self.scrollArea.setWidget(self.canvas) 
     self.toolbar = NavigationToolbar(self.canvas, self.scrollArea) 

     self.canvas2 = FigureCanvas(self.figure) 
     self.scrollArea2.setWidget(self.canvas2) 
     self.toolbar2 = NavigationToolbar(self.canvas2, self.scrollArea2) 

     self.gs = gridspec.GridSpec(1, 1) 
     self.ax = self.figure.add_subplot(self.gs[0]) 
     self.ax2 = self.figure.add_subplot(self.gs[0]) 
     self.figure.subplots_adjust(left=0.05) 

     self.ax.clear() 

    def start_streamsignal(self, start=True): 
     # open and start the stream 
     if start is True: 
      print("start Signals") 

      self.p = pyaudio.PyAudio() 
      self.stream = self.p.open(format=pyaudio.paFloat32, channels=self.channels, rate=self.fs, input_device_index=1, 
          output_device_index=5, input=True, frames_per_buffer=self.Chunks) 
      print("recording...") 

    def start_streamread(self): 
     """return values for Chunks of stream""" 
     data = self.stream.read(self.Chunks) 
     npframes2 = np.array(data).flatten() 
     npframes2 = np.fromstring(npframes2, dtype=np.float32) 

     norm_audio2 = (npframes2/np.max(np.abs(npframes2))) # normalize 
     left2 = norm_audio2[::2] 
     right2 = norm_audio2[1::2] 
     print(norm_audio2) 
     return left2, right2 

    def tape_add(self): 
     """add chunks to tape""" 
     self.tape[:-self.Chunks] = self.tape[self.Chunks:] 
     self.taper = self.tape 
     self.tapel = self.tape 
     self.taper[-self.Chunks:], self.tapel[-self.Chunks:] = self.start_streamread() 

    def plot(self, use_blit=True): 
     # Plot the Tape and update chunks 
     print('Plotting') 
     self.start_streamsignal(start=True) 
     start = True 

     for duration in range(0, 15, 1): 
      plotsec = 1 
      time.sleep(2) 
      self.timeArray = np.arange(self.taper.size) 
      self.timeArray = (self.timeArray/self.fs) * 1000 # scale to milliseconds 
      self.tape_add() 

      # self.canvas.draw() 
      while start is True and plotsec < 3: 

       # self.ani = animation.FuncAnimation(self.figure, self.animate, interval=25, blit=True) 
       self.ax2.plot(self.taper, '-b') 
       self.canvas.draw() 

       self.ax2.clear() 
       self.ax2.plot(self.tapel, 'g-') 
       self.canvas2.draw() 

       plotsec += 1 

    def animate(self): 
     self.line.set_xdata(self.taper) 
     return self.line, 


def main(): 
    app = QtWidgets.QApplication(sys.argv) 
    GUI = Window() 
    GUI.show() 
    sys.exit(app.exec_()) 

main() 
+0

認沽''QApplication.processEvents在環()。 – Chris

+0

或用'canvas2.draw_idle()'替換'canvas2.draw()'。無論如何,代碼太大,無法調試。如果上述任何評論無法解決您的問題,請嘗試撰寫一個有關問題的最簡單示例。 SO不打算用於在100行代碼上尋求幫助。 –

+0

@Chris,這段小小的代碼('QtWidgets.QApplication.processEvents()')使程序工作起來應該是完美的。非常感謝你。 – Audiosnow

回答

0

感謝所有幫助,這裏是現在工作的代碼,如果有人感興趣:

import sys 
from PyQt5 import QtGui, QtWidgets, QtCore 
import numpy as np 
import time 
import pyaudio 
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas 
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar 
from matplotlib.figure import Figure 
import matplotlib.gridspec as gridspec 
import matplotlib.animation as animation 


class Window(QtWidgets.QMainWindow): 

    def __init__(self): # sort of template for rest of GUI, is always there, menubar/ mainmenu eg. 
     super(Window, self).__init__() 
     self.setGeometry(50, 50, 1500, 900) 
     self.setWindowTitle("PyQt Tutorial!") 

     self.centralwidget = QtWidgets.QWidget(self) 
     self.centralwidget.setObjectName("centralwidget") 

     self.channels = 2 
     self.fs = 44100 # samplerate 
     self.Chunks = 1024 

     self.tapeLength = 2 # seconds 
     self.tape = np.empty(self.fs * self.tapeLength) * np.nan # tapes where recorded audio is stored 

     self.home() 

    def home(self): 
     btn = QtWidgets.QPushButton("Stream and Plot", self) # Button to start streaming 
     btn.clicked.connect(self.plot) 
     btn.resize(btn.sizeHint()) 
     btn.move(100, 100) 

     self.scrollArea = QtWidgets.QScrollArea(self) 
     self.scrollArea.move(75, 400) 
     self.scrollArea.resize(600, 300) 
     self.scrollArea.setWidgetResizable(False) 

     self.scrollArea2 = QtWidgets.QScrollArea(self) 
     self.scrollArea2.move(775, 400) 
     self.scrollArea2.resize(600, 300) 
     self.scrollArea2.setWidgetResizable(False) 
     self.scrollArea.horizontalScrollBar().valueChanged.connect(self.scrollArea2.horizontalScrollBar().setValue) 
     self.scrollArea2.horizontalScrollBar().valueChanged.connect(self.scrollArea.horizontalScrollBar().setValue) 

     self.figure = Figure((15, 2.8), dpi=100) # figure instance (to plot on) F(width, height, ...) 
     self.canvas = FigureCanvas(self.figure) 
     self.scrollArea.setWidget(self.canvas) 
     self.toolbar = NavigationToolbar(self.canvas, self.scrollArea) 

     self.canvas2 = FigureCanvas(self.figure) 
     self.scrollArea2.setWidget(self.canvas2) 
     self.toolbar2 = NavigationToolbar(self.canvas2, self.scrollArea2) 

     self.gs = gridspec.GridSpec(1, 1) 
     self.ax = self.figure.add_subplot(self.gs[0]) 
     self.ax2 = self.figure.add_subplot(self.gs[0]) 
     self.figure.subplots_adjust(left=0.05) 

     self.ax.clear() 

    def start_streamsignal(self, start=True): 
    # open and start the stream 
     if start is True: 
      print("start Signals") 

      self.p = pyaudio.PyAudio() 
      self.stream = self.p.open(format=pyaudio.paFloat32, channels=self.channels, rate=self.fs, input_device_index=1, 
         output_device_index=5, input=True, frames_per_buffer=self.Chunks) 
      print("recording...") 

    def start_streamread(self): 
    """return values for Chunks of stream""" 
     data = self.stream.read(self.Chunks) 
     npframes2 = np.array(data).flatten() 
     npframes2 = np.fromstring(npframes2, dtype=np.float32) 

     norm_audio2 = (npframes2/np.max(np.abs(npframes2))) # normalize 
     left2 = norm_audio2[::2] 
     right2 = norm_audio2[1::2] 
     print(norm_audio2) 
     return left2, right2 

    def tape_add(self): 
    """add chunks to tape""" 
     self.tape[:-self.Chunks] = self.tape[self.Chunks:] 
     self.taper = self.tape 
     self.tapel = self.tape 
     self.taper[-self.Chunks:], self.tapel[-self.Chunks:] = self.start_streamread() 

    def plot(self, use_blit=True): 
    # Plot the Tape and update chunks 
     print('Plotting') 
     self.start_streamsignal(start=True) 
     start = True 

     for duration in range(0, 15, 1): 
      QtWidgets.QApplication.processEvents() 
      plotsec = 1 
      time.sleep(2) 
      self.timeArray = np.arange(self.taper.size) 
      self.timeArray = (self.timeArray/self.fs) * 1000 # scale to milliseconds 
      self.tape_add() 

      while start is True and plotsec < 3: 

       self.ax.plot(self.taper, '-b') 
       self.canvas.draw() 

       self.ax2.clear() 
       self.ax2.plot(self.tapel, 'g-') 
       self.canvas2.draw() 

       plotsec += 1 


def main(): 
    app = QtWidgets.QApplication(sys.argv) 
    GUI = Window() 
    GUI.show() 
    sys.exit(app.exec_()) 

main() 
1

我有嚴重問題的理解完整的代碼,以什麼所有的東西在裏面實際上應該做的。所以我現在可以告訴你的是,你可能想擺脫循環,並使用FuncAnimation來顯示動畫。

def plot(self, use_blit=True): 
     # Plot the Tape and update chunks 
     print('Plotting') 
     self.start_streamsignal(start=True) 
     start = True 
     self.line, = self.ax2.plot([],[], '-b') 
     self.ax.set_xlim(0, len(self.tape)) 
     self.ax2.set_xlim(0, len(self.tape)) 
     self.ax.set_ylim(-3, 3) 
     self.ax2.set_ylim(-3, 3) 

     self.ani = animation.FuncAnimation(self.figure, self.animate, frames=100, 
             interval=25, blit=use_blit) 


    def animate(self,i): 
     self.timeArray = np.arange(self.taper.size) 
     self.timeArray = (self.timeArray/self.fs) * 1000 # scale to milliseconds 
     self.tape_add() 
     self.line.set_data(range(len(self.taper)),self.taper) 
     return self.line, 
+0

對不起,我應該對代碼提出更多評論,我知道這一點。謝謝,但是隨着程序員使用循環,我不再需要動畫部分。 – Audiosnow