Ejemplo n.º 1
0
    def __init__(self,nskip=3):

        self.interval = nskip+1
        self.n = 0
        qadi = QAudioDeviceInfo()
        codecs = qadi.supportedCodecs()
        codec_exists = len(codecs)
        self.active = ('audio_directory' in dir(ccfg) and 'error_tones' in dir(ccfg))
        self.tone_dict = {}
Ejemplo n.º 2
0
    def __init__(self, startupDelay: float) -> None:
        threading.Thread.__init__(self)
        self.startupDelay = startupDelay
        self.finish = False
        if isMac and qtminor > 12:
            # trigger permission prompt
            from PyQt5.QtMultimedia import QAudioDeviceInfo

            QAudioDeviceInfo.defaultInputDevice()
Ejemplo n.º 3
0
    def __init__(self, output_path: str, startup_delay: float) -> None:
        threading.Thread.__init__(self)
        self._output_path = output_path
        self._startup_delay = startup_delay
        self.finish = False
        # though we're using pyaudio here, we rely on Qt to trigger
        # the permission prompt on macOS
        if isMac and qtminor > 12:
            from PyQt5.QtMultimedia import QAudioDeviceInfo

            QAudioDeviceInfo.defaultInputDevice()
Ejemplo n.º 4
0
    def __init__(self, parent=None):
        print("Tone Widget inst")
        QWidget.__init__(self, parent)

        self.activeGen = ActiveGen(sampleRate=SAMPLE_RATE,
                                   samplePerRead=Meep.SAMPLES_PER_READ)
        self.createUI(self)

        # Meep playback format initialization
        format = QAudioFormat()
        format.setChannelCount(AUDIO_CHANS)
        format.setSampleRate(SAMPLE_RATE)
        format.setSampleSize(SAMPLE_SIZE)
        format.setCodec("audio/pcm")
        format.setByteOrder(QAudioFormat.LittleEndian)
        format.setSampleType(QAudioFormat.SignedInt)

        # check compatibility of format with device
        info = QAudioDeviceInfo(QAudioDeviceInfo.defaultOutputDevice())
        if info.isFormatSupported(format) is False:
            print(
                "Raw audio format not supported by backend, cannot play audio."
            )
            return None

        # Audio Output init
        self.output = QAudioOutput(format, self)
        output_buffer_size = \
            int(2*SAMPLE_RATE \
                 *CTRL_INTERVAL/1000)
        self.output.setBufferSize(output_buffer_size)
        # initialize and start the audio playback
        self.generator = Meep(format, self.activeGen, self)
        self.generator.start()
        self.output.start(self.generator)

        # Create the port reader object
        self.midiListener = MidiPortReader()
        # Create a thread which will read it
        self.listenerThread = QThread()

        # move QObjet to a new thread
        self.midiListener.moveToThread(self.listenerThread)

        # Connect the signals to slot functions
        self.midiListener.newNoteFrequency.connect(self.activeGen.setFreq)
        self.midiListener.newNotePress.connect(self.activeGen.setNote)

        # Tell Qt the function to call
        # when it starts the thread
        self.listenerThread.started.connect(self.midiListener.listener)
        # start the thread
        self.listenerThread.start()
Ejemplo n.º 5
0
   def __init__(self, parent=None):
      super().__init__(parent)    #调用父类构造函数,创建窗体
      self.ui=Ui_MainWindow()     #创建UI对象
      self.ui.setupUi(self)       #构造UI界面

      self.ui.progBar_Max.setMaximum(256)
      self.ui.progBar_Min.setMaximum(256)
      self.ui.progBar_Diff.setMaximum(256)

      self.ui.sliderVolumn.setMaximum(100)
      self.ui.sliderVolumn.setValue(100)

      self.ui.comboDevices.clear()
      self.__deviceList=QAudioDeviceInfo.availableDevices(QAudio.AudioInput) #音频输入设备列表
      for i in range(len(self.__deviceList)):
         device=self.__deviceList[i]    #QAudioDeviceInfo类
         self.ui.comboDevices.addItem(device.deviceName())

##      self.__deviceInfo =None   #当前设备信息,QAudioDeviceInfo
      self.audioDevice=None       #音频输入设备,QAudioInput
      self.BUFFER_SIZE=4000

      self.ioDevice=None      #第1种读取方法,内建的IODevice

##      self.externalReader=None        #第2种读取方法,外建的IODevice

      self.recordFile=QFile()      #第3种读取方法,使用QFile直接写入文件

      if len(self.__deviceList)>0:
         self.ui.comboDevices.setCurrentIndex(0) #触发comboDevices的信号currentIndexChanged()
##         self.__deviceInfo =deviceList[0]
      else:
         self.ui.actStart.setEnabled(False)
         self.ui.actDeviceTest.setEnabled(False)
         self.ui.groupBoxDevice.setTitle("支持的音频输入设置(无设备)")
Ejemplo n.º 6
0
    def __init__(self, output_path: str, mw: aqt.AnkiQt,
                 parent: QWidget) -> None:
        super().__init__(output_path)

        self.mw = mw
        self._parent = parent

        from PyQt5.QtMultimedia import QAudioDeviceInfo, QAudioFormat, QAudioInput

        format = QAudioFormat()
        format.setChannelCount(1)
        format.setSampleRate(44100)
        format.setSampleSize(16)
        format.setCodec("audio/pcm")
        format.setByteOrder(QAudioFormat.LittleEndian)
        format.setSampleType(QAudioFormat.SignedInt)

        device = QAudioDeviceInfo.defaultInputDevice()
        if not device.isFormatSupported(format):
            format = device.nearestFormat(format)
            print("format changed")
            print("channels", format.channelCount())
            print("rate", format.sampleRate())
            print("size", format.sampleSize())
        self._format = format

        self._audio_input = QAudioInput(device, format, parent)
Ejemplo n.º 7
0
 def initAUD(self):
     #
     info = QAudioDeviceInfo.defaultInputDevice()
     if (~info.isFormatSupported(self.audio.format)):
         # print("警告,设置的默认音频格式并不支持,将尝试采用最相近的支持格式")
         # 不知道这里面有什么神改动?
         self.audio.format  = info.nearestFormat(self.audio.format)
     #
     update_interval = 160
     self.audioRecorder = QAudioInput(self.audio.format)
     self.audioRecorder.setNotifyInterval(update_interval) #按毫秒ms 类似于QTimer的作用
     self.audioRecorder.notify.connect(self.processAudioData)
     self.audioRecorder_TD = QThread()
     self.audioRecorder.moveToThread(self.audioRecorder_TD)
     self.audioRecorder_TD.started.connect(self.startRecord)
     self.audioRecorder.stateChanged.connect(self.recordStopped)
     # 总结来说线程只是一个容器,里面执行的循环要是没法结束,强制退出也不好操作
     # 所以还是好好写好任务流然后发送信号比较合理
     self.audioPlayer = QAudioOutput(self.audio.format)
     self.audioPlayer.setNotifyInterval(update_interval)
     self.audioPlayer.notify.connect(self.processAudioData)
     self.audioPlayer_TD = QThread()
     self.audioPlayer.moveToThread(self.audioPlayer_TD)
     self.audioPlayer_TD.started.connect(self.startPlay)
     self.audioPlayer.stateChanged.connect(self.playStopped)
Ejemplo n.º 8
0
    def initializeWindow(self):
        layout = QVBoxLayout()

        self.m_deviceBox = QComboBox(activated=self.deviceChanged)
        for deviceInfo in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput):
            self.m_deviceBox.addItem(deviceInfo.deviceName(), deviceInfo)

        layout.addWidget(self.m_deviceBox)

        self.m_modeButton = QPushButton(clicked=self.toggleMode)
        self.m_modeButton.setText(self.PUSH_MODE_LABEL)

        layout.addWidget(self.m_modeButton)

        self.m_suspendResumeButton = QPushButton(
                clicked=self.toggleSuspendResume)
        self.m_suspendResumeButton.setText(self.SUSPEND_LABEL)

        layout.addWidget(self.m_suspendResumeButton)

        volumeBox = QHBoxLayout()
        volumeLabel = QLabel("Volume:")
        self.m_volumeSlider = QSlider(Qt.Horizontal, minimum=0, maximum=100,
                singleStep=10, valueChanged=self.volumeChanged)
        volumeBox.addWidget(volumeLabel)
        volumeBox.addWidget(self.m_volumeSlider)

        layout.addLayout(volumeBox)

        window = QWidget()
        window.setLayout(layout)

        self.setCentralWidget(window)
Ejemplo n.º 9
0
    def initializeWindow(self):
        layout = QVBoxLayout()

        self.m_deviceBox = QComboBox(activated=self.deviceChanged)
        for deviceInfo in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput):
            self.m_deviceBox.addItem(deviceInfo.deviceName(), deviceInfo)

        layout.addWidget(self.m_deviceBox)

        self.m_modeButton = QPushButton(clicked=self.toggleMode)
        self.m_modeButton.setText(self.PUSH_MODE_LABEL)

        layout.addWidget(self.m_modeButton)

        self.m_suspendResumeButton = QPushButton(
                clicked=self.toggleSuspendResume)
        self.m_suspendResumeButton.setText(self.SUSPEND_LABEL)

        layout.addWidget(self.m_suspendResumeButton)

        volumeBox = QHBoxLayout()
        volumeLabel = QLabel("Volume:")
        self.m_volumeSlider = QSlider(Qt.Horizontal, minimum=0, maximum=100,
                singleStep=10, valueChanged=self.volumeChanged)
        volumeBox.addWidget(volumeLabel)
        volumeBox.addWidget(self.m_volumeSlider)

        layout.addLayout(volumeBox)

        window = QWidget()
        window.setLayout(layout)

        self.setCentralWidget(window)
Ejemplo n.º 10
0
    def setupUi(self, MainWindow):
        self.threadpool = QtCore.QThreadPool()
        MainWindow.setObjectName("MainWindow")

        sizeObject = QtWidgets.QDesktopWidget().screenGeometry(-1)

        H = (sizeObject.height())
        W = (sizeObject.width())

        self.W = W
        self.H = H
        MainWindow.resize(W//8, H//10)
        MainWindow.setMinimumSize(QtCore.QSize(W//5, H//7))
        MainWindow.setAcceptDrops(True)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem('')
        self.cmd = ""
        """ AUDIO and VIDIO DEVICES """
        from PyQt5.QtMultimedia import QAudioDeviceInfo, QAudio, QCameraInfo
        # List of Audio Input Devices
        input_audio_deviceInfos = QAudioDeviceInfo.availableDevices(
            QAudio.AudioInput)
        for device in input_audio_deviceInfos:
            self.comboBox.addItem(device.deviceName())
        """ ----------------------  """
        self.comboBox.setCurrentIndex(1)
        self.Mic = input_audio_deviceInfos[0].deviceName()
        self.gridLayout.addWidget(self.comboBox, 1, 0, 1, 1)
        self.radioButton = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton.setObjectName("radioButton")
        self.gridLayout.addWidget(self.radioButton, 2, 0, 1, 1)
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setMinimumSize(QtCore.QSize(0, 23))
        self.pushButton.setIconSize(QtCore.QSize(16, 25))
        self.pushButton.setObjectName("pushButton")
        self.gridLayout.addWidget(self.pushButton, 3, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionNew = QtWidgets.QAction(MainWindow)
        self.actionNew.setObjectName("actionNew")
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.clicked = False
        self.pushButton.clicked.connect(self.takeSnapNow)
        self.radioButton.toggled.connect(self.setStatus)
        self.comboBox.currentIndexChanged[str].connect(self.setAudioDevice)
        self.th = {}
        self.cap = ""
        self.useCam = False
        self.st = 0
        self.arguments = ''
        self.process = None
Ejemplo n.º 11
0
 def modeChanged(self, idx: int) -> None:
     self.testResult.clear()
     self.deviceBox.clear()
     mode = QAudio.AudioInput if idx == 0 else QAudio.AudioOutput
     for deviceInfo in QAudioDeviceInfo.availableDevices(mode):
         self.deviceBox.addItem(deviceInfo.deviceName(), deviceInfo)
     self.deviceBox.setCurrentIndex(0)
     self.deviceChanged(0)
Ejemplo n.º 12
0
    def __init__(self):
        super(AudioTest, self).__init__()

        self.m_device = QAudioDeviceInfo.defaultOutputDevice()
        self.m_output = None

        self.initializeWindow()
        self.initializeAudio()
Ejemplo n.º 13
0
    def __init__(self):
        super(AudioTest, self).__init__()

        self.m_device = QAudioDeviceInfo.defaultOutputDevice()
        self.m_output = None

        self.initializeWindow()
        self.initializeAudio()
Ejemplo n.º 14
0
    def update_info_choices(self):
        if self.behaviour_play_button == self.behaviour_play_button_restart:
            self.behaviour_tab.option_play_button.radio_restart.setChecked(
                True)
        else:
            self.behaviour_tab.option_play_button.radio_nothing.setChecked(
                True)

        if self.behaviour_playlist_autoplay == self.behaviour_playlist_autoplay_start:
            self.behaviour_tab.option_playlist_autoplay.radio_autoplay.setChecked(
                True)
        else:
            self.behaviour_tab.option_playlist_autoplay.radio_no_autoplay.setChecked(
                True)

        self.behaviour_tab.option_scrolling_text.spin_millisecond.setValue(
            self.mainwindow.options.get_default_option(
                self.mainwindow.options.default_user_timer_interval,
                self.mainwindow.options.default_app_timer_interval))

        self.audio_tab.option_output_device.label_selected_device.setToolTip(
            self.mainwindow.options.get_default_output_device())
        self.audio_tab.option_output_device.label_selected_device.setText(
            "Current: {}".format(
                self.mainwindow.options.get_default_output_device()))

        self.audio_tab.option_output_device.combo_box_selected_device.clear()
        for device in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput):
            self.audio_tab.option_output_device.combo_box_selected_device.addItem(
                device.deviceName())
            if self.audio_tab.option_output_device.combo_box_selected_device.count(
            ) == len(QAudioDeviceInfo.availableDevices(
                    QAudio.AudioOutput)) / 2:
                self.audio_tab.option_output_device.combo_box_selected_device.addItem(
                    self.mainwindow.options.default_app_output_device)
                break
        for text, index in util.get_all_combo_box_items(
                self.audio_tab.option_output_device.combo_box_selected_device):
            if text == self.mainwindow.options.get_default_output_device():
                self.audio_tab.option_output_device.combo_box_selected_device.setCurrentIndex(
                    index)
Ejemplo n.º 15
0
    def initializeAudio(self):
        self.m_pullTimer = QTimer(self, timeout=self.pullTimerExpired)
        self.m_pullMode = True

        self.m_format = QAudioFormat()
        self.m_format.setSampleRate(self.DataSampleRateHz)
        self.m_format.setChannelCount(1)
        self.m_format.setSampleSize(16)
        self.m_format.setCodec('audio/pcm')
        self.m_format.setByteOrder(QAudioFormat.LittleEndian)
        self.m_format.setSampleType(QAudioFormat.SignedInt)

        info = QAudioDeviceInfo(QAudioDeviceInfo.defaultOutputDevice())
        if not info.isFormatSupported(self.m_format):
            qWarning("Default format not supported - trying to use nearest")
            self.m_format = info.nearestFormat(self.m_format)

        self.m_generator = Generator(self.m_format,
                self.DurationSeconds * 1000000, self.ToneSampleRateHz, self)

        self.createAudioOutput()
Ejemplo n.º 16
0
    def initializeAudio(self):
        self.m_pullTimer = QTimer(self, timeout=self.pullTimerExpired)
        self.m_pullMode = True

        self.m_format = QAudioFormat()
        self.m_format.setSampleRate(self.DataSampleRateHz)
        self.m_format.setChannelCount(1)
        self.m_format.setSampleSize(16)
        self.m_format.setCodec('audio/pcm')
        self.m_format.setByteOrder(QAudioFormat.LittleEndian)
        self.m_format.setSampleType(QAudioFormat.SignedInt)

        info = QAudioDeviceInfo(QAudioDeviceInfo.defaultOutputDevice())
        if not info.isFormatSupported(self.m_format):
            qWarning("Default format not supported - trying to use nearest")
            self.m_format = info.nearestFormat(self.m_format)

        self.m_generator = Generator(self.m_format,
                self.DurationSeconds * 1000000, self.ToneSampleRateHz, self)

        self.createAudioOutput()
Ejemplo n.º 17
0
    def __init__(self, parent=None):
        super(AudioTest, self).__init__(parent)

        self.deviceInfo = QAudioDeviceInfo()
        self.settings = QAudioFormat()
        self.mode = QAudio.AudioOutput

        self.testButton.clicked.connect(self.test)
        self.modeBox.activated.connect(self.modeChanged)
        self.deviceBox.activated.connect(self.deviceChanged)
        self.sampleRateBox.activated.connect(self.sampleRateChanged)
        self.channelsBox.activated.connect(self.channelChanged)
        self.codecsBox.activated.connect(self.codecChanged)
        self.sampleSizesBox.activated.connect(self.sampleSizeChanged)
        self.sampleTypesBox.activated.connect(self.sampleTypeChanged)
        self.endianBox.activated.connect(self.endianChanged)
        self.populateTableButton.clicked.connect(self.populateTable)

        self.modeBox.setCurrentIndex(0)
        self.modeChanged(0)
        self.deviceBox.setCurrentIndex(0)
        self.deviceChanged(0)
Ejemplo n.º 18
0
    def __init__(self, parent=None):

        QWidget.__init__(self, parent)

        format = QAudioFormat()
        format.setChannelCount(1)
        format.setSampleRate(22050)
        format.setSampleSize(16)
        format.setCodec("audio/pcm")
        format.setByteOrder(QAudioFormat.LittleEndian)
        format.setSampleType(QAudioFormat.SignedInt)
        self.output = QAudioOutput(format, self)

        self.frequency = 440
        self.volume = 0
        self.buffer = QBuffer()
        self.data = QByteArray()

        self.deviceLineEdit = QLineEdit()
        self.deviceLineEdit.setReadOnly(True)
        self.deviceLineEdit.setText(
            QAudioDeviceInfo.defaultOutputDevice().deviceName())

        self.pitchSlider = QSlider(Qt.Horizontal)
        self.pitchSlider.setMaximum(100)
        self.volumeSlider = QSlider(Qt.Horizontal)
        self.volumeSlider.setMaximum(32767)
        self.volumeSlider.setPageStep(1024)

        self.playButton = QPushButton(self.tr("&Play"))

        self.pitchSlider.valueChanged.connect(self.changeFrequency)
        self.volumeSlider.valueChanged.connect(self.changeVolume)
        self.playButton.clicked.connect(self.play)

        formLayout = QFormLayout()
        formLayout.addRow(self.tr("Device:"), self.deviceLineEdit)
        formLayout.addRow(self.tr("P&itch:"), self.pitchSlider)
        formLayout.addRow(self.tr("&Volume:"), self.volumeSlider)

        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(self.playButton)
        buttonLayout.addStretch()

        horizontalLayout = QHBoxLayout(self)
        horizontalLayout.addLayout(formLayout)
        horizontalLayout.addLayout(buttonLayout)

        self.play()
        self.createData()
Ejemplo n.º 19
0
    def modeChanged(self, idx):
        self.testResult.clear()

        if idx == 0:
            self.mode = QAudio.AudioInput
        else:
            self.mode = QAudio.AudioOutput

        self.deviceBox.clear()
        for deviceInfo in QAudioDeviceInfo.availableDevices(self.mode):
            self.deviceBox.addItem(deviceInfo.deviceName(), deviceInfo)

        self.deviceBox.setCurrentIndex(0)
        self.deviceChanged(0)
Ejemplo n.º 20
0
    def modeChanged(self, idx):
        self.testResult.clear()

        if idx == 0:
            self.mode = QAudio.AudioInput
        else:
            self.mode = QAudio.AudioOutput

        self.deviceBox.clear()
        for deviceInfo in QAudioDeviceInfo.availableDevices(self.mode):
            self.deviceBox.addItem(deviceInfo.deviceName(), deviceInfo)

        self.deviceBox.setCurrentIndex(0)
        self.deviceChanged(0)
Ejemplo n.º 21
0
 def __init__(self, obj):
     super().__init__(obj)
     self.mode = None
     self.colors = None
     self.count = 0
     # noinspection PyArgumentList
     self.inputdevices = QAudioDeviceInfo.availableDevices(
         QAudio.AudioInput)
     self.input = None
     if self.inputdevices:
         self.changeinput(0)
     self.stream = None
     self.timer = QTimer()
     # connections
     # noinspection PyUnresolvedReferences
     self.timer.timeout.connect(self.setcolorinterrupt)
     self.main.ui.plainTextEdit_bitdetector.textChanged.connect(
         self.checkinput)
     self.main.ui.comboBox_input.currentIndexChanged.connect(
         self.changeinput)
     self.main.ui.comboBox_effect_music.currentIndexChanged.connect(
         self.changetextedit)
     self.main.ui.pushButton_color_low.clicked.connect(self.colorselector)
     self.main.ui.pushButton_color_mid.clicked.connect(self.colorselector)
     self.main.ui.pushButton_color_high.clicked.connect(self.colorselector)
     self.main.ui.verticalSlider_lower_low.valueChanged.connect(
         self.changeslider)
     self.main.ui.verticalSlider_lower_mid.valueChanged.connect(
         self.changeslider)
     self.main.ui.verticalSlider_lower_high.valueChanged.connect(
         self.changeslider)
     self.main.ui.verticalSlider_higher_low.valueChanged.connect(
         self.changeslider)
     self.main.ui.verticalSlider_higher_mid.valueChanged.connect(
         self.changeslider)
     self.main.ui.verticalSlider_higher_high.valueChanged.connect(
         self.changeslider)
     self.main.ui.pushButton_sound_onoff.toggled.connect(
         self.soundbuttononoff)
     # update styles
     effects = ['Smooth', 'Change', 'Flash', 'Strob']
     self.main.ui.comboBox_effect_music.addItems(effects)
     inputs = [i.deviceName() for i in self.inputdevices]
     self.main.ui.comboBox_input.addItems(inputs)
     self.updatebuttons()
    def __init__(self):
        super().__init__()

        self.m_chart = QChart()

        chart_view = QChartView(self.m_chart)
        chart_view.setMinimumSize(800, 600)

        self.m_series = QLineSeries()
        self.m_chart.addSeries(self.m_series)

        axis_x = QValueAxis()
        axis_x.setRange(0, 2000)
        axis_x.setLabelFormat("%g")
        axis_x.setTitleText("Samples")

        axis_y = QValueAxis()
        axis_y.setRange(-1, 1)
        axis_y.setTitleText("Audio level")

        self.m_chart.setAxisX(axis_x, self.m_series)
        self.m_chart.setAxisY(axis_y, self.m_series)
        self.m_chart.setTitle("Data from the microphone")

        main_layout = QVBoxLayout()
        main_layout.addWidget(chart_view)
        self.setLayout(main_layout)

        format_audio = QAudioFormat()
        format_audio.setSampleRate(48000)
        format_audio.setChannelCount(1)
        format_audio.setSampleSize(8)
        format_audio.setCodec("audio/pcm")
        format_audio.setByteOrder(QAudioFormat.LittleEndian)
        format_audio.setSampleType(QAudioFormat.UnSignedInt)

        input_devices = QAudioDeviceInfo.defaultInputDevice()
        self.m_audio_input = QAudioInput(input_devices, format_audio)

        self.m_device = XYSeriesIODevice(self.m_series)
        self.m_device.open(QIODevice.WriteOnly)

        self.m_audio_input.start(self.m_device)

        self.init_ui()
Ejemplo n.º 23
0
    def __init__(self, parent: QWidget = None) -> None:
        super().__init__(parent)

        self.m_deviceInfo: QAudioDeviceInfo = QAudioDeviceInfo()
        self.m_settings: QAudioFormat = QAudioFormat()

        self.testButton.clicked.connect(self.test)
        self.modeBox.activated[int].connect(self.modeChanged)
        self.deviceBox.activated[int].connect(self.deviceChanged)
        self.sampleRateBox.activated[int].connect(self.sampleRateChanged)
        self.channelsBox.activated[int].connect(self.channelChanged)
        self.codecsBox.activated[int].connect(self.codecChanged)
        self.sampleSizesBox.activated[int].connect(self.sampleSizeChanged)
        self.sampleTypesBox.activated[int].connect(self.sampleTypeChanged)
        self.endianBox.activated[int].connect(self.endianChanged)
        self.populateTableButton.clicked.connect(self.populateTable)

        self.modeBox.setCurrentIndex(0)
        self.modeChanged(0)
        self.deviceBox.setCurrentIndex(0)
        self.deviceChanged(0)
Ejemplo n.º 24
0
    def __init__(self, parent=None):
        super(AudioTest, self).__init__(parent)

        self.deviceInfo = QAudioDeviceInfo()
        self.settings = QAudioFormat()
        self.mode = QAudio.AudioOutput

        self.testButton.clicked.connect(self.test)
        self.modeBox.activated.connect(self.modeChanged)
        self.deviceBox.activated.connect(self.deviceChanged)
        self.sampleRateBox.activated.connect(self.sampleRateChanged)
        self.channelsBox.activated.connect(self.channelChanged)
        self.codecsBox.activated.connect(self.codecChanged)
        self.sampleSizesBox.activated.connect(self.sampleSizeChanged)
        self.sampleTypesBox.activated.connect(self.sampleTypeChanged)
        self.endianBox.activated.connect(self.endianChanged)
        self.populateTableButton.clicked.connect(self.populateTable)

        self.modeBox.setCurrentIndex(0)
        self.modeChanged(0)
        self.deviceBox.setCurrentIndex(0)
        self.deviceChanged(0)
Ejemplo n.º 25
0
 def load(self):
     """
     Load the settings
     """
     self.auto_start_check_box.setChecked(
         Settings().value(self.settings_section + '/media auto start'))
     self.stream_cmd.setText(Settings().value(self.settings_section +
                                              '/stream command'))
     self.audio_edit.setText(Settings().value(self.settings_section +
                                              '/audio'))
     self.video_edit.setText(Settings().value(self.settings_section +
                                              '/video'))
     if not self.stream_cmd.text():
         self.set_base_stream()
     self.vlc_arguments_edit.setPlainText(
         Settings().value(self.settings_section + '/vlc arguments'))
     if Settings().value('advanced/experimental'):
         # vlc.MediaPlayer().audio_output_device_enum()
         for cam in QCameraInfo.availableCameras():
             log.debug(cam.deviceName())
             log.debug(cam.description())
         for au in QAudioDeviceInfo.availableDevices(QAudio.AudioInput):
             log.debug(au.deviceName())
def stoprecording_func():
    p.send_signal(signal.CTRL_C_EVENT)
    start_record_btn.configure(state=tk.NORMAL)
    screen_shot_btn.configure(state=tk.NORMAL)
    browse_btn.configure(state=tk.NORMAL)
    save_btn.configure(state=tk.NORMAL)
    tk.messagebox.showinfo(
        'Info', 'Recording file ->' + video_filename + '\nSaved at ->' +
        entry_text.get())


screenshot_filename = 'screenshots_' + time.strftime("%Y%m%d-%H%M%S")
default_path = 'C:/Users/vikesh/Desktop'
doc_suffix = '.docx'
video_suffix = '.mp4'
input_audio_devices = QAudioDeviceInfo.availableDevices(QAudio.AudioInput)
devices = []
for device in input_audio_devices:
    if device.deviceName() not in devices:
        devices.append(device.deviceName())

document = Document()
window = tk.Tk()
window.configure(background='#767676')
window.resizable(width=False, height=False)
window.title('Recorder')

style = Style()
style.theme_use('clam')
style.configure('TButton',
                font=('Segoe', 9, 'bold'),
Ejemplo n.º 27
0
class AudioTest(AudioDevicesBase):

    def __init__(self, parent=None):
        super(AudioTest, self).__init__(parent)

        self.deviceInfo = QAudioDeviceInfo()
        self.settings = QAudioFormat()
        self.mode = QAudio.AudioOutput

        self.testButton.clicked.connect(self.test)
        self.modeBox.activated.connect(self.modeChanged)
        self.deviceBox.activated.connect(self.deviceChanged)
        self.sampleRateBox.activated.connect(self.sampleRateChanged)
        self.channelsBox.activated.connect(self.channelChanged)
        self.codecsBox.activated.connect(self.codecChanged)
        self.sampleSizesBox.activated.connect(self.sampleSizeChanged)
        self.sampleTypesBox.activated.connect(self.sampleTypeChanged)
        self.endianBox.activated.connect(self.endianChanged)
        self.populateTableButton.clicked.connect(self.populateTable)

        self.modeBox.setCurrentIndex(0)
        self.modeChanged(0)
        self.deviceBox.setCurrentIndex(0)
        self.deviceChanged(0)

    def test(self):
        self.testResult.clear()

        if not self.deviceInfo.isNull():
            if self.deviceInfo.isFormatSupported(self.settings):
                self.testResult.setText("Success")
                self.nearestSampleRate.setText("")
                self.nearestChannel.setText("")
                self.nearestCodec.setText("")
                self.nearestSampleSize.setText("")
                self.nearestSampleType.setText("")
                self.nearestEndian.setText("")
            else:
                nearest = self.deviceInfo.nearestFormat(self.settings)
                self.testResult.setText("Failed")
                self.nearestSampleRate.setText(str(nearest.sampleRate()))
                self.nearestChannel.setText(str(nearest.channelCount()))
                self.nearestCodec.setText(nearest.codec())
                self.nearestSampleSize.setText(str(nearest.sampleSize()))
                self.nearestSampleType.setText(
                        self.sampleTypeToString(nearest.sampleType()))
                self.nearestEndian.setText(
                        self.endianToString(nearest.byteOrder()))
        else:
            self.testResult.setText("No Device")

    sampleTypeMap = {
        QAudioFormat.SignedInt: "SignedInt",
        QAudioFormat.UnSignedInt: "UnSignedInt",
        QAudioFormat.Float: "Float"
    }

    @classmethod
    def sampleTypeToString(cls, sampleType):
        return cls.sampleTypeMap.get(sampleType, "Unknown")

    endianMap = {
        QAudioFormat.LittleEndian: "LittleEndian",
        QAudioFormat.BigEndian: "BigEndian"
    }

    @classmethod
    def endianToString(cls, endian):
        return cls.endianMap.get(endian, "Unknown")

    def modeChanged(self, idx):
        self.testResult.clear()

        if idx == 0:
            self.mode = QAudio.AudioInput
        else:
            self.mode = QAudio.AudioOutput

        self.deviceBox.clear()
        for deviceInfo in QAudioDeviceInfo.availableDevices(self.mode):
            self.deviceBox.addItem(deviceInfo.deviceName(), deviceInfo)

        self.deviceBox.setCurrentIndex(0)
        self.deviceChanged(0)

    def deviceChanged(self, idx):
        self.testResult.clear()

        if self.deviceBox.count() == 0:
            return

        self.deviceInfo = self.deviceBox.itemData(idx)

        self.sampleRateBox.clear()
        sampleRatez = self.deviceInfo.supportedSampleRates()
        self.sampleRateBox.addItems([str(sr) for sr in sampleRatez])
        if len(sampleRatez) != 0:
            self.settings.setSampleRate(sampleRatez[0])

        self.channelsBox.clear()
        chz = self.deviceInfo.supportedChannelCounts()
        self.channelsBox.addItems([str(ch) for ch in chz])
        if len(chz) != 0:
            self.settings.setChannelCount(chz[0])

        self.codecsBox.clear()
        codecs = self.deviceInfo.supportedCodecs()
        self.codecsBox.addItems([str(c) for c in codecs])
        if len(codecs) != 0:
            self.settings.setCodec(codecs[0])

        # Create a failed condition.
        self.codecsBox.addItem("audio/test")

        self.sampleSizesBox.clear()
        sampleSizez = self.deviceInfo.supportedSampleSizes()
        self.sampleSizesBox.addItems([str(ss) for ss in sampleSizez])
        if len(sampleSizez) != 0:
            self.settings.setSampleSize(sampleSizez[0])

        self.sampleTypesBox.clear()
        sampleTypez = self.deviceInfo.supportedSampleTypes()
        self.sampleTypesBox.addItems(
                [self.sampleTypeToString(st) for st in sampleTypez])
        if len(sampleTypez) != 0:
            self.settings.setSampleType(sampleTypez[0])

        self.endianBox.clear()
        endianz = self.deviceInfo.supportedByteOrders()
        self.endianBox.addItems([self.endianToString(e) for e in endianz])
        if len(endianz) != 0:
            self.settings.setByteOrder(endianz[0])

        self.allFormatsTable.clearContents()

    def populateTable(self):
        row = 0
        format = QAudioFormat()

        for codec in self.deviceInfo.supportedCodecs():
            format.setCodec(codec)

            for sampleRate in self.deviceInfo.supportedSampleRates():
                format.setSampleRate(sampleRate)

                for channels in self.deviceInfo.supportedChannelCounts():
                    format.setChannelCount(channels)

                    for sampleType in self.deviceInfo.supportedSampleTypes():
                        format.setSampleType(sampleType)

                        for sampleSize in self.deviceInfo.supportedSampleSizes():
                            format.setSampleSize(sampleSize)

                            for endian in self.deviceInfo.supportedByteOrders():
                                format.setByteOrder(endian)

                                if self.deviceInfo.isFormatSupported(format):
                                    self.allFormatsTable.setRowCount(row + 1)

                                    self.setFormatValue(row, 0, format.codec())
                                    self.setFormatValue(row, 1,
                                            str(format.sampleRate()))
                                    self.setFormatValue(row, 2,
                                            str(format.channelCount()))
                                    self.setFormatValue(row, 3,
                                            self.sampleTypeToString(
                                                    format.sampleType()))
                                    self.setFormatValue(row, 4,
                                            str(format.sampleSize()))
                                    self.setFormatValue(row, 5,
                                            self.endianToString(
                                                    format.byteOrder()))

                                    row += 1

    def setFormatValue(self, row, column, value):
        self.allFormatsTable.setItem(row, column, QTableWidgetItem(value))

    def sampleRateChanged(self, idx):
        self.settings.setSampleRate(int(self.sampleRateBox.itemText(idx)))

    def channelChanged(self, idx):
        self.settings.setChannelCount(int(self.channelsBox.itemText(idx)))

    def codecChanged(self, idx):
        self.settings.setCodec(self.codecsBox.itemText(idx))

    def sampleSizeChanged(self, idx):
        self.settings.setSampleSize(int(self.sampleSizesBox.itemText(idx)))

    def sampleTypeChanged(self, idx):
        sampleType = int(self.sampleTypesBox.itemText(idx))

        if sampleType == QAudioFormat.SignedInt:
            self.settings.setSampleType(QAudioFormat.SignedInt)
        elif sampleType == QAudioFormat.UnSignedInt:
            self.settings.setSampleType(QAudioFormat.UnSignedInt)
        elif sampleType == QAudioFormat.Float:
            self.settings.setSampleType(QAudioFormat.Float)

    def endianChanged(self, idx):
        endian = int(self.endianBox.itemText(idx))

        if endian == QAudioFormat.LittleEndian:
            self.settings.setByteOrder(QAudioFormat.LittleEndian)
        elif endian == QAudioFormat.BigEndian:
            self.settings.setByteOrder(QAudioFormat.BigEndian)
Ejemplo n.º 28
0
 def get_audio_devices(self):
     return QAudioDeviceInfo.availableDevices(QAudio.AudioOutput)
Ejemplo n.º 29
0
class AudioTest(AudioDevicesBase):
    def __init__(self, parent=None):
        super(AudioTest, self).__init__(parent)

        self.deviceInfo = QAudioDeviceInfo()
        self.settings = QAudioFormat()
        self.mode = QAudio.AudioOutput

        self.testButton.clicked.connect(self.test)
        self.modeBox.activated.connect(self.modeChanged)
        self.deviceBox.activated.connect(self.deviceChanged)
        self.sampleRateBox.activated.connect(self.sampleRateChanged)
        self.channelsBox.activated.connect(self.channelChanged)
        self.codecsBox.activated.connect(self.codecChanged)
        self.sampleSizesBox.activated.connect(self.sampleSizeChanged)
        self.sampleTypesBox.activated.connect(self.sampleTypeChanged)
        self.endianBox.activated.connect(self.endianChanged)
        self.populateTableButton.clicked.connect(self.populateTable)

        self.modeBox.setCurrentIndex(0)
        self.modeChanged(0)
        self.deviceBox.setCurrentIndex(0)
        self.deviceChanged(0)

    def test(self):
        self.testResult.clear()

        if not self.deviceInfo.isNull():
            if self.deviceInfo.isFormatSupported(self.settings):
                self.testResult.setText("Success")
                self.nearestSampleRate.setText("")
                self.nearestChannel.setText("")
                self.nearestCodec.setText("")
                self.nearestSampleSize.setText("")
                self.nearestSampleType.setText("")
                self.nearestEndian.setText("")
            else:
                nearest = self.deviceInfo.nearestFormat(self.settings)
                self.testResult.setText("Failed")
                self.nearestSampleRate.setText(str(nearest.sampleRate()))
                self.nearestChannel.setText(str(nearest.channelCount()))
                self.nearestCodec.setText(nearest.codec())
                self.nearestSampleSize.setText(str(nearest.sampleSize()))
                self.nearestSampleType.setText(
                    self.sampleTypeToString(nearest.sampleType()))
                self.nearestEndian.setText(
                    self.endianToString(nearest.byteOrder()))
        else:
            self.testResult.setText("No Device")

    sampleTypeMap = {
        QAudioFormat.SignedInt: "SignedInt",
        QAudioFormat.UnSignedInt: "UnSignedInt",
        QAudioFormat.Float: "Float"
    }

    @classmethod
    def sampleTypeToString(cls, sampleType):
        return cls.sampleTypeMap.get(sampleType, "Unknown")

    endianMap = {
        QAudioFormat.LittleEndian: "LittleEndian",
        QAudioFormat.BigEndian: "BigEndian"
    }

    @classmethod
    def endianToString(cls, endian):
        return cls.endianMap.get(endian, "Unknown")

    def modeChanged(self, idx):
        self.testResult.clear()

        if idx == 0:
            self.mode = QAudio.AudioInput
        else:
            self.mode = QAudio.AudioOutput

        self.deviceBox.clear()
        for deviceInfo in QAudioDeviceInfo.availableDevices(self.mode):
            self.deviceBox.addItem(deviceInfo.deviceName(), deviceInfo)

        self.deviceBox.setCurrentIndex(0)
        self.deviceChanged(0)

    def deviceChanged(self, idx):
        self.testResult.clear()

        if self.deviceBox.count() == 0:
            return

        self.deviceInfo = self.deviceBox.itemData(idx)

        self.sampleRateBox.clear()
        sampleRatez = self.deviceInfo.supportedSampleRates()
        self.sampleRateBox.addItems([str(sr) for sr in sampleRatez])
        if len(sampleRatez) != 0:
            self.settings.setSampleRate(sampleRatez[0])

        self.channelsBox.clear()
        chz = self.deviceInfo.supportedChannelCounts()
        self.channelsBox.addItems([str(ch) for ch in chz])
        if len(chz) != 0:
            self.settings.setChannelCount(chz[0])

        self.codecsBox.clear()
        codecs = self.deviceInfo.supportedCodecs()
        self.codecsBox.addItems([str(c) for c in codecs])
        if len(codecs) != 0:
            self.settings.setCodec(codecs[0])

        # Create a failed condition.
        self.codecsBox.addItem("audio/test")

        self.sampleSizesBox.clear()
        sampleSizez = self.deviceInfo.supportedSampleSizes()
        self.sampleSizesBox.addItems([str(ss) for ss in sampleSizez])
        if len(sampleSizez) != 0:
            self.settings.setSampleSize(sampleSizez[0])

        self.sampleTypesBox.clear()
        sampleTypez = self.deviceInfo.supportedSampleTypes()
        self.sampleTypesBox.addItems(
            [self.sampleTypeToString(st) for st in sampleTypez])
        if len(sampleTypez) != 0:
            self.settings.setSampleType(sampleTypez[0])

        self.endianBox.clear()
        endianz = self.deviceInfo.supportedByteOrders()
        self.endianBox.addItems([self.endianToString(e) for e in endianz])
        if len(endianz) != 0:
            self.settings.setByteOrder(endianz[0])

        self.allFormatsTable.clearContents()

    def populateTable(self):
        row = 0
        format = QAudioFormat()

        for codec in self.deviceInfo.supportedCodecs():
            format.setCodec(codec)

            for sampleRate in self.deviceInfo.supportedSampleRates():
                format.setSampleRate(sampleRate)

                for channels in self.deviceInfo.supportedChannelCounts():
                    format.setChannelCount(channels)

                    for sampleType in self.deviceInfo.supportedSampleTypes():
                        format.setSampleType(sampleType)

                        for sampleSize in self.deviceInfo.supportedSampleSizes(
                        ):
                            format.setSampleSize(sampleSize)

                            for endian in self.deviceInfo.supportedByteOrders(
                            ):
                                format.setByteOrder(endian)

                                if self.deviceInfo.isFormatSupported(format):
                                    self.allFormatsTable.setRowCount(row + 1)

                                    self.setFormatValue(row, 0, format.codec())
                                    self.setFormatValue(
                                        row, 1, str(format.sampleRate()))
                                    self.setFormatValue(
                                        row, 2, str(format.channelCount()))
                                    self.setFormatValue(
                                        row, 3,
                                        self.sampleTypeToString(
                                            format.sampleType()))
                                    self.setFormatValue(
                                        row, 4, str(format.sampleSize()))
                                    self.setFormatValue(
                                        row, 5,
                                        self.endianToString(
                                            format.byteOrder()))

                                    row += 1

    def setFormatValue(self, row, column, value):
        self.allFormatsTable.setItem(row, column, QTableWidgetItem(value))

    def sampleRateChanged(self, idx):
        self.settings.setSampleRate(int(self.sampleRateBox.itemText(idx)))

    def channelChanged(self, idx):
        self.settings.setChannelCount(int(self.channelsBox.itemText(idx)))

    def codecChanged(self, idx):
        self.settings.setCodec(self.codecsBox.itemText(idx))

    def sampleSizeChanged(self, idx):
        self.settings.setSampleSize(int(self.sampleSizesBox.itemText(idx)))

    def sampleTypeChanged(self, idx):
        sampleType = int(self.sampleTypesBox.itemText(idx))

        if sampleType == QAudioFormat.SignedInt:
            self.settings.setSampleType(QAudioFormat.SignedInt)
        elif sampleType == QAudioFormat.UnSignedInt:
            self.settings.setSampleType(QAudioFormat.UnSignedInt)
        elif sampleType == QAudioFormat.Float:
            self.settings.setSampleType(QAudioFormat.Float)

    def endianChanged(self, idx):
        endian = int(self.endianBox.itemText(idx))

        if endian == QAudioFormat.LittleEndian:
            self.settings.setByteOrder(QAudioFormat.LittleEndian)
        elif endian == QAudioFormat.BigEndian:
            self.settings.setByteOrder(QAudioFormat.BigEndian)
Ejemplo n.º 30
0
    def _uic(self):
        '''
    set up our layout which consists of:

                 Big Honkin' Label
        [input combobox]    [output combobox]
               [volume slider]  [x] Mute

    Hooking the signals to useful slots is the job
    of __init__. Here just make the layout.
        '''
        self.setMinimumWidth(400)
        # Create the big honkin' label and logo
        icon_pixmap = QPixmap(':/icon.png').scaledToWidth(64)
        icon_label = QLabel()
        icon_label.setPixmap(icon_pixmap)
        text_label = QLabel("Sidetone!")
        hb_label = QHBoxLayout()
        hb_label.addStretch(1)
        hb_label.addWidget(icon_label, 0)
        hb_label.addWidget(text_label, 0)
        hb_label.addStretch(1)

        # Create a list of QAudioInfo objects for inputs
        self.input_info_list = QAudioDeviceInfo.availableDevices(
            QAudio.AudioInput)
        if 0 == len(self.input_info_list):
            self.input_info_list = [QAudioDeviceInfo.defaultInputDevice()]
        # Make a list of the name-strings for those items.
        in_dev_names = [
            audio_info.deviceName() for audio_info in self.input_info_list
        ]
        # Create a combo box and populate it with those names
        self.cb_inputs = QComboBox()
        self.cb_inputs.addItems(in_dev_names)
        # If the in_dev_name from the previous run is in the current list,
        # make it current, otherwise pick the first item.
        in_dev_name = self.settings.value('in_dev_name', 'unknown')
        if in_dev_name in in_dev_names:
            self.cb_inputs.setCurrentIndex(in_dev_names.index(in_dev_name))
        else:
            self.cb_inputs.setCurrentIndex(0)

        # Create a list of QAudioInfo objects for outputs
        self.otput_info_list = QAudioDeviceInfo.availableDevices(
            QAudio.AudioOutput)
        if 0 == len(self.otput_info_list):
            self.otput_info_list = [QAudioDeviceInfo.defaultOutputDevice()]
        # Make a list of the name-strings of those things
        ot_dev_names = [
            audio_info.deviceName() for audio_info in self.otput_info_list
        ]
        # Create a combo box and populate it with those names
        self.cb_otputs = QComboBox()
        self.cb_otputs.addItems(ot_dev_names)
        # If the ot_dev_name from the previous run is in the current list,
        # make it the current choice in the box.
        ot_dev_name = self.settings.value('ot_dev_name', 'unknown')
        if ot_dev_name in ot_dev_names:
            self.cb_otputs.setCurrentIndex(ot_dev_names.index(ot_dev_name))
        else:
            self.cb_otputs.setCurrentIndex(0)

        #self.show_status(
        #'{} inputs {} otputs'.format(len(self.input_info_list),len(self.otput_info_list))
        #)
        # Create a combo box and populate it with names of outputs

        # Lay those two out aligned to the outside
        hb_combos = QHBoxLayout()
        hb_combos.addWidget(self.cb_inputs, 1)
        hb_combos.addStretch(0)
        hb_combos.addWidget(self.cb_otputs, 1)

        # Create a volume slider from 0 to 100.
        self.volume = QSlider(Qt.Horizontal, self)
        self.volume.setMinimum(0)
        self.volume.setMaximum(100)
        self.volume.setTickInterval(10)
        self.volume.setTickPosition(QSlider.TicksBothSides)
        # set the volume slider to the value from the previous run, or zero.
        self.volume.setValue(self.settings.value('volume', 0))

        # Create a checkbox "Mute"
        self.mute = QCheckBox('Mute')
        # Set it to the value at the end of the last run, or to True
        self.mute.setChecked(bool(self.settings.value('mute_status', 1)))

        # Put those together in a row squeezed in the center
        hb_volume = QHBoxLayout()
        hb_volume.addStretch(1)
        hb_volume.addWidget(self.volume, 1)
        hb_volume.addWidget(self.mute, 0)
        hb_volume.addStretch(1)

        # Stack all those up as this widget's layout
        vlayout = QVBoxLayout()
        vlayout.addLayout(hb_label)
        vlayout.addLayout(hb_combos)
        vlayout.addLayout(hb_volume)
        self.setLayout(vlayout)
Ejemplo n.º 31
0
    def initUI(self):
        
        # main window/layout
        window = QWidget()
        layout = QVBoxLayout()
        
        # layout for audio device and sample rate selection
        deviceLayout = QHBoxLayout()
        
        # make audio device selection box and list of available devices
        self.deviceBox = QComboBox()
        defaultDeviceInfo = QAudioDeviceInfo.defaultInputDevice()
        self.availableDevices = [defaultDeviceInfo]
        self.availableDevices += QAudioDeviceInfo.availableDevices(
                                                             QAudio.AudioInput)
        for device in self.availableDevices:
            self.deviceBox.addItem(device.deviceName())
            
        # make sample rate label and combobox
        sRateLabel = QLabel("Sample rate:")
        sRateLabel.setAlignment(Qt.AlignRight)
        
        # user can choose between 44.1 and 48kHz (valid DetectorBank rates)
        self.sRateBox = QComboBox()
        self.sRateBox.addItem("44100")
        self.sRateBox.addItem("48000")
        self.sRateBox.setCurrentIndex(1)
        
        # add device and sr widgets to device layout
        deviceLayout.addWidget(self.deviceBox)
        deviceLayout.addWidget(sRateLabel)
        deviceLayout.addWidget(self.sRateBox)
        
        # add device layout to main layout
        layout.addLayout(deviceLayout)
        
        # DetectorBank parameters layout
        # two rows of three parameters
        # each param needs label and edit, 
        # and a 'Start' button will be added at the bottom
        # so grid should be 3x6
        detBankParamLayout = QGridLayout()
        
        # label and lineedit for each
        bandwidthLabel = QLabel("Bandwidth (cents):")
        dampingLabel = QLabel("Damping:")
        gainLabel = QLabel("Gain:")
        edoLabel = QLabel("EDO:")
        lwrLabel = QLabel("Lower note:")
        uprLabel = QLabel("Upper note:")
        
        self.bandwidthEdit = QLineEdit("0")
        self.dampingEdit = QLineEdit("0.0001")
        self.gainEdit = QLineEdit("25")
        self.edoEdit = QLineEdit("12")
        self.lwrEdit = QLineEdit("A1")
        self.uprEdit = QLineEdit("A7")
        
        # store all in lists
        detBankParamLabels = [bandwidthLabel, dampingLabel, gainLabel, 
                              edoLabel, lwrLabel, uprLabel]
        
        detBankParamEdits = [self.bandwidthEdit, self.dampingEdit, 
                             self.gainEdit, self.edoEdit, self.lwrEdit, 
                             self.uprEdit]
         
        # fill first two rows of grid with labels and edits
        row = 0

        for row in range(2):
            widgetNum = 0
        
            for i in range((row*3), (row*3)+3):
                detBankParamLayout.addWidget(detBankParamLabels[i], row, 
                                             widgetNum)
                widgetNum += 1
                detBankParamLayout.addWidget(detBankParamEdits[i], row, 
                                             widgetNum)
                widgetNum += 1
            
        # align labels to the right (next to the edit)
        for i in range(len(detBankParamLabels)):
            detBankParamLabels[i].setAlignment(Qt.AlignRight)
                
        # button to make DetectorBank and start visualisation
        row += 1
        startButton = QPushButton("&Start!")
        detBankParamLayout.addWidget(startButton, row, 5)
        startButton.clicked.connect(self.start)
        
        # add grid of detbank params (and start button) to main layout
        layout.addLayout(detBankParamLayout)
        
        window.setLayout(layout)
        self.setCentralWidget(window)
        self.show()
Ejemplo n.º 32
0
class Options(object):
    default_app_options_file = "./options.json"
    default_app_volume = 25
    default_app_timer_interval = 200
    default_app_play_button_behaviour = 1
    default_app_last_folder_opened = "/"
    default_app_playlist_autoplay = 1
    default_app_output_device = QAudioDeviceInfo.defaultOutputDevice().deviceName()

    json_volume_name = "default_volume"
    json_timer_name = "default_timer_interval"
    json_play_button_name = "default_play_button_behaviour"
    json_music_folders_name = "music_folders"
    json_last_folder_opened_name = "default_last_folder_opened"
    json_playlist_autoplay = "default_playlist_autoplay"
    json_output_device = "default_output_device"

    def __init__(self):
        self.default_user_volume = None
        self.default_user_timer_interval = None
        self.default_user_play_button_behaviour = None
        self.user_music_folders = None
        self.default_user_last_folder_opened = None
        self.default_user_playlist_autoplay = None
        self.default_user_output_device = None

        self.json_user_defaults = None

        self.get_user_defaults()

    @staticmethod
    def get_default_option(user_option, app_option):
        if user_option is None:
            return app_option
        else:
            return user_option

    def get_default_volume(self):
        return self.get_default_option(self.default_user_volume, self.default_app_volume)

    def get_default_timer_interval(self):
        return self.get_default_option(self.default_user_timer_interval, self.default_app_timer_interval)

    def get_default_play_button(self):
        return self.get_default_option(self.default_user_play_button_behaviour, self.default_app_play_button_behaviour)

    def get_default_last_folder_opened(self):
        return self.get_default_option(self.default_user_last_folder_opened, self.default_app_last_folder_opened)

    def get_default_playlist_autoplay(self):
        return self.get_default_option(self.default_user_playlist_autoplay, self.default_app_playlist_autoplay)

    def get_default_output_device(self):
        return self.get_default_option(self.default_user_output_device, self.default_app_output_device)

    def get_user_defaults(self):
        if not os.path.exists(self.default_app_options_file):
            return

        with open(self.default_app_options_file, 'r') as file:
            if os.stat(self.default_app_options_file).st_size == 0:  # If the file is empty
                return

            self.json_user_defaults = json.load(file)

            self.default_user_volume = self.set_user_default(self.json_volume_name)
            self.default_user_timer_interval = self.set_user_default(self.json_timer_name)
            self.default_user_play_button_behaviour = self.set_user_default(self.json_play_button_name)
            self.user_music_folders = self.set_user_default(self.json_music_folders_name)
            self.default_user_last_folder_opened = self.set_user_default(self.json_last_folder_opened_name)
            self.default_user_playlist_autoplay = self.set_user_default(self.json_playlist_autoplay)
            self.default_user_output_device = self.set_user_default(self.json_output_device)

    def save_user_defaults(self, volume=None, timer_interval=None, play_button_behaviour=None, music_folder=None,
                           last_folder_opened=None, playlist_autoplay=None, output_device=None):
        if volume is None:
            volume = self.get_default_volume()
        else:
            self.default_user_volume = volume

        if timer_interval is None:
            timer_interval = self.get_default_timer_interval()
        else:
            self.default_user_timer_interval = timer_interval

        if play_button_behaviour is None:
            play_button_behaviour = self.get_default_play_button()
        else:
            self.default_user_play_button_behaviour = play_button_behaviour

        if music_folder is not None:
            if self.user_music_folders is None:
                # list(self.user_music_folders).append(music_folder)
                self.user_music_folders = [music_folder]
            else:
                self.user_music_folders.append(music_folder)

        if last_folder_opened is None:
            last_folder_opened = self.get_default_last_folder_opened()
        else:
            self.default_user_last_folder_opened = last_folder_opened

        if playlist_autoplay is None:
            playlist_autoplay = self.get_default_playlist_autoplay()
        else:
            self.default_user_playlist_autoplay = playlist_autoplay

        if output_device is None:
            output_device = self.get_default_output_device()
        else:
            self.default_user_output_device = output_device

        info_dicts = {'{}'.format(self.json_volume_name): volume,
                      '{}'.format(self.json_timer_name): timer_interval,
                      '{}'.format(self.json_play_button_name): play_button_behaviour,
                      self.json_music_folders_name: self.user_music_folders,
                      '{}'.format(self.json_last_folder_opened_name): last_folder_opened,
                      '{}'.format(self.json_playlist_autoplay): playlist_autoplay,
                      '{}'.format(self.json_output_device): output_device}
        json_string = json.dumps(info_dicts, indent=4, separators=(',', ' : '))

        with open(self.default_app_options_file, 'w') as file:
            file.write(json_string)

    def delete_music_folder(self, folder):
        try:
            self.user_music_folders.remove(folder)
        except ValueError:
            return
        info_dicts = {'{}'.format(self.json_volume_name): self.default_user_volume,
                      '{}'.format(self.json_timer_name): self.default_user_timer_interval,
                      '{}'.format(self.json_play_button_name): self.default_user_play_button_behaviour,
                      self.json_music_folders_name: self.user_music_folders,
                      '{}'.format(self.json_last_folder_opened_name): self.default_user_last_folder_opened,
                      '{}'.format(self.json_playlist_autoplay): self.default_user_playlist_autoplay,
                      '{}'.format(self.json_output_device): self.default_user_output_device}
        json_string = json.dumps(info_dicts, indent=4, separators=(',', ' : '))

        with open(self.default_app_options_file, 'w') as file:
            file.write(json_string)

    def set_user_default(self, option_name):
        try:
            return self.json_user_defaults[option_name]
        except KeyError:
            return None
Ejemplo n.º 33
0
    def __init__(self):
        super().__init__()

        arguments = self.parseArguments()

        self.DEBUG = arguments.debug

        os.chdir(os.path.dirname(os.path.realpath(__file__)))

        self.MIN_WIDTH = 600
        self.MIN_HEIGHT = 350

        self.setMinimumWidth(self.MIN_WIDTH)
        self.setMinimumHeight(self.MIN_HEIGHT)

        self.ROOT_FOLDER = os.path.expanduser("~/.florodoro/")

        self.HISTORY_FILE_PATH = self.ROOT_FOLDER + "history" + ("" if not self.DEBUG else "-debug") + ".yaml"
        self.CONFIGURATION_FILE_PATH = self.ROOT_FOLDER + "config" + ("" if not self.DEBUG else "-debug") + ".yaml"

        self.history = History(self.HISTORY_FILE_PATH)

        self.SOUNDS_FOLDER = "sounds/"
        self.PLANTS_FOLDER = "plants/"
        self.IMAGE_FOLDER = "images/"

        self.TEXT_COLOR = self.palette().text().color()
        self.BREAK_COLOR = "#B37700"

        self.APP_NAME = "Florodoro"

        self.STUDY_ICON = qtawesome.icon('fa5s.book', color=self.TEXT_COLOR)
        self.BREAK_ICON = qtawesome.icon('fa5s.coffee', color=self.BREAK_COLOR)
        self.CONTINUE_ICON = qtawesome.icon('fa5s.play', color=self.TEXT_COLOR)
        self.PAUSE_ICON = qtawesome.icon('fa5s.pause', color=self.TEXT_COLOR)
        self.RESET_ICON = qtawesome.icon('fa5s.undo', color=self.TEXT_COLOR)

        self.PLANTS = [GreenTree, DoubleGreenTree, OrangeTree, CircularFlower]
        self.PLANT_NAMES = ["Spruce", "Double spruce", "Maple", "Flower"]

        self.WIDGET_SPACING = 10

        self.MAX_TIME = 180
        self.STEP = 5

        self.INITIAL_TEXT = "Start!"

        self.menuBar = QMenuBar(self)
        self.presets_menu = self.menuBar.addMenu('&Presets')

        self.presets = {
            "Classic": (25, 5, 4),
            "Extended": (45, 12, 2),
            "Sitcomodoro": (65, 25, 1),
        }

        for name in self.presets:
            study_time, break_time, cycles = self.presets[name]

            self.presets_menu.addAction(
                QAction(f"{name} ({study_time} : {break_time} : {cycles})", self,
                        triggered=partial(self.load_preset, study_time, break_time, cycles)))

        self.DEFAULT_PRESET = "Classic"

        self.options_menu = self.menuBar.addMenu('&Options')

        self.notify_menu = self.options_menu.addMenu("&Notify")

        self.sound_action = QAction("&Sound", self, checkable=True, checked=not self.DEBUG,
                                    triggered=lambda _: self.volume_slider.setDisabled(
                                        not self.sound_action.isChecked()))

        self.notify_menu.addAction(self.sound_action)

        # Default audio device
        self.audio_device = QAudioDeviceInfo.defaultInputDevice()

        # Create device menu
        self.audio_device_menu = self.notify_menu.addMenu("&Audio Devices")

        # For all sound devices, add a device check box to the device menu
        audio_devices = QAudioDeviceInfo.availableDevices(QAudio.AudioOutput)

        for device in audio_devices:
            device_name = device.deviceName()
            self.device_action = QAction(f"&{device_name}", self, checkable=True, checked=not self.DEBUG, triggered=partial(self.setAudioDevice, device))
            # Create callback of some sort for clicking on the device in the menu
            self.audio_device_menu.addAction(self.device_action)

        self.volume_slider = QSlider(Qt.Horizontal, minimum=0, maximum=100, value=85)
        slider_action = QWidgetAction(self)
        slider_action.setDefaultWidget(SpacedQWidget(self.volume_slider))
        self.notify_menu.addAction(slider_action)

        self.popup_action = QAction("&Pop-up", self, checkable=True, checked=True)
        self.notify_menu.addAction(self.popup_action)

        self.menuBar.addAction(
            QAction(
                "&Statistics",
                self,
                triggered=lambda: self.statistics.show() if self.statistics.isHidden() else self.statistics.hide()
            )
        )

        self.menuBar.addAction(
            QAction(
                "&About",
                self,
                triggered=lambda: QMessageBox.information(
                    self,
                    "About",
                    "This application was created by Tomáš Sláma. It is heavily inspired by the Android app Forest, "
                    "but with all of the plants generated procedurally. It's <a href='https://github.com/xiaoxiae/Florodoro'>open source</a> and licensed "
                    "under MIT, so do as you please with the code and anything else related to the project.",
                ),
            )
        )

        self.plant_menu = self.options_menu.addMenu("&Plants")

        self.overstudy_action = QAction("Overstudy", self, checkable=True)
        self.options_menu.addAction(self.overstudy_action)

        self.plant_images = []
        self.plant_checkboxes = []

        # dynamically create widgets for each plant
        for plant, name in zip(self.PLANTS, self.PLANT_NAMES):
            self.plant_images.append(tempfile.NamedTemporaryFile(suffix=".svg"))
            tmp = plant()
            tmp.set_max_age(1)
            tmp.set_age(1)
            tmp.save(self.plant_images[-1].name, 200, 200)

            setattr(self.__class__, name,
                    QAction(self, icon=QIcon(self.plant_images[-1].name), text=name, checkable=True, checked=True))

            action = getattr(self.__class__, name)

            self.plant_menu.addAction(action)
            self.plant_checkboxes.append(action)

        # the current plant that we're growing
        # if set to none, no plant is growing
        self.plant = None

        self.menuBar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)

        main_vertical_layout = QVBoxLayout(self)
        main_vertical_layout.setContentsMargins(0, 0, 0, 0)
        main_vertical_layout.setSpacing(0)
        main_vertical_layout.addWidget(self.menuBar)

        self.canvas = Canvas(self)

        self.statistics = Statistics(self.history)

        font = self.font()
        font.setPointSize(100)

        self.main_label = QLabel(self, alignment=Qt.AlignCenter)
        self.main_label.setFont(font)
        self.main_label.setText(self.INITIAL_TEXT)

        font.setPointSize(26)
        self.cycle_label = QLabel(self)
        self.cycle_label.setAlignment(Qt.AlignTop)
        self.cycle_label.setMargin(20)
        self.cycle_label.setFont(font)

        main_horizontal_layout = QHBoxLayout(self)

        self.study_time_spinbox = QSpinBox(self, prefix="Study for: ", suffix="min.", minimum=1, maximum=self.MAX_TIME,
                                           singleStep=self.STEP)

        self.break_time_spinbox = QSpinBox(self, prefix="Break for: ", suffix="min.", minimum=1, maximum=self.MAX_TIME,
                                           singleStep=self.STEP,
                                           styleSheet=f'color:{self.BREAK_COLOR};')

        self.cycles_spinbox = QSpinBox(self, prefix="Cycles: ", minimum=1, value=1)

        # keep track of remaining number of cycles and the starting number of cycles
        self.remaining_cycles = 0
        self.total_cycles = 0

        # whether we're currently studying
        self.is_study_ongoing = False

        # whether we notified the user already during overstudy
        self.already_notified_during_overstudy = False

        stacked_layout = QStackedLayout(self, stackingMode=QStackedLayout.StackAll)
        stacked_layout.addWidget(self.main_label)
        stacked_layout.addWidget(self.cycle_label)
        stacked_layout.addWidget(self.canvas)

        main_vertical_layout.addLayout(stacked_layout)

        self.setStyleSheet("")

        self.study_button = QPushButton(self, clicked=self.start, icon=self.STUDY_ICON)
        self.break_button = QPushButton(self, clicked=self.start_break, icon=self.BREAK_ICON)
        self.pause_button = QPushButton(self, clicked=self.toggle_pause, icon=self.PAUSE_ICON)
        self.reset_button = QPushButton(self, clicked=self.reset, icon=self.RESET_ICON)

        main_horizontal_layout.addWidget(self.study_time_spinbox)
        main_horizontal_layout.addWidget(self.break_time_spinbox)
        main_horizontal_layout.addWidget(self.cycles_spinbox)
        main_horizontal_layout.addWidget(self.study_button)
        main_horizontal_layout.addWidget(self.break_button)
        main_horizontal_layout.addWidget(self.pause_button)
        main_horizontal_layout.addWidget(self.reset_button)

        main_vertical_layout.addLayout(main_horizontal_layout)

        self.setLayout(main_vertical_layout)

        self.study_timer_frequency = 1 / 60 * 1000
        self.study_timer = QTimer(self, interval=int(self.study_timer_frequency), timeout=self.decrease_remaining_time)

        self.player = QMediaPlayer(self)

        self.setWindowIcon(QIcon(self.IMAGE_FOLDER + "icon.svg"))
        self.setWindowTitle(self.APP_NAME)

        # set initial UI state
        self.reset()

        # a list of name, getter and setter things to load/save when the app opens/closes
        # also dynamically get settings for selecting/unselecting plants
        self.CONFIGURATION_ATTRIBUTES = [("study-time", self.study_time_spinbox.value,
                                          self.study_time_spinbox.setValue),
                                         ("break-time", self.break_time_spinbox.value,
                                          self.break_time_spinbox.setValue),
                                         ("cycles", self.cycles_spinbox.value, self.cycles_spinbox.setValue),
                                         ("sound", self.sound_action.isChecked, self.sound_action.setChecked),
                                         ("sound-volume", self.volume_slider.value, self.volume_slider.setValue),
                                         ("pop-ups", self.popup_action.isChecked, self.popup_action.setChecked),
                                         ("overstudy", self.overstudy_action.isChecked,
                                          self.overstudy_action.setChecked)] + \
                                        [(name.lower(), getattr(self.__class__, name).isChecked,
                                          getattr(self.__class__, name).setChecked) for _, name in
                                         zip(self.PLANTS, self.PLANT_NAMES)]
        # load the default preset
        self.load_preset(*self.presets[self.DEFAULT_PRESET])

        self.load_settings()
        self.show()
Ejemplo n.º 34
0
    def _uic(self):
        """
    set up our layout which consists of:

                 Big Honkin' Label
        [input combobox]    [output combobox]
               [volume slider]  [x] Mute

    hooking put the signals to useful slots is the job
    of __init__. Here just make the layout.
        """
        self.setMinimumWidth(400)
        # Create the big honkin' label and logo
        icon_pixmap = QPixmap(":/icon.png").scaledToWidth(64)
        icon_label = QLabel()
        icon_label.setPixmap(icon_pixmap)
        text_label = QLabel("Sidetone!")
        hb_label = QHBoxLayout()
        hb_label.addStretch(1)
        hb_label.addWidget(icon_label, 0)
        hb_label.addWidget(text_label, 0)
        hb_label.addStretch(1)

        # Create a list of QAudioInfo objects for inputs
        self.input_info_list = QAudioDeviceInfo.availableDevices(QAudio.AudioInput)
        if 0 == len(self.input_info_list):
            self.input_info_list = [QAudioDeviceInfo.defaultInputDevice()]
        # Create a combo box and populate it with names of inputs
        self.cb_inputs = QComboBox()
        self.cb_inputs.addItems([audio_info.deviceName() for audio_info in self.input_info_list])
        # Create a list of QAudioInfo objects for outputs
        self.otput_info_list = QAudioDeviceInfo.availableDevices(QAudio.AudioOutput)
        if 0 == len(self.otput_info_list):
            self.otput_info_list = [QAudioDeviceInfo.defaultOutputDevice()]
        self.status_bar.showMessage(
            "{} inputs {} otputs".format(len(self.input_info_list), len(self.otput_info_list)), 2000
        )
        # Create a combo box and populate it with names of outputs
        self.cb_otputs = QComboBox()
        self.cb_otputs.addItems([audio_info.deviceName() for audio_info in self.otput_info_list])
        # Lay those two out aligned to the outside
        hb_combos = QHBoxLayout()
        hb_combos.addWidget(self.cb_inputs, 1)
        hb_combos.addStretch(0)
        hb_combos.addWidget(self.cb_otputs, 1)
        # Create a volume slider from 0 to 100.
        self.volume = QSlider(Qt.Horizontal, self)
        self.volume.setMinimum(0)
        self.volume.setMaximum(100)
        self.volume.setTickInterval(10)
        self.volume.setTickPosition(QSlider.TicksBothSides)
        # Create a checkbox "Mute"
        self.mute = QCheckBox("Mute")
        # Put those together in a row squeezed in the center
        hb_volume = QHBoxLayout()
        hb_volume.addStretch(1)
        hb_volume.addWidget(self.volume, 1)
        hb_volume.addWidget(self.mute, 0)
        hb_volume.addStretch(1)
        # Stack all those up as this widget's layout
        vlayout = QVBoxLayout()
        vlayout.addLayout(hb_label)
        vlayout.addLayout(hb_combos)
        vlayout.addLayout(hb_volume)
        self.setLayout(vlayout)
Ejemplo n.º 35
0
    def _uic(self):
        '''
    set up our layout which consists of:

                 Big Honkin' Label
        [input combobox]    [output combobox]
               [volume slider]  [x] Mute

    hooking put the signals to useful slots is the job
    of __init__. Here just make the layout.
        '''
        self.setMinimumWidth(400)
        # Create the big honkin' label and logo
        icon_pixmap = QPixmap(':/icon.png').scaledToWidth(64)
        icon_label = QLabel()
        icon_label.setPixmap(icon_pixmap)
        text_label = QLabel("Sidetone!")
        hb_label = QHBoxLayout()
        hb_label.addStretch(1)
        hb_label.addWidget(icon_label, 0)
        hb_label.addWidget(text_label, 0)
        hb_label.addStretch(1)

        # Create a list of QAudioInfo objects for inputs
        self.input_info_list = QAudioDeviceInfo.availableDevices(
            QAudio.AudioInput)
        if 0 == len(self.input_info_list):
            self.input_info_list = [QAudioDeviceInfo.defaultInputDevice()]
        # Create a combo box and populate it with names of inputs
        self.cb_inputs = QComboBox()
        self.cb_inputs.addItems(
            [audio_info.deviceName() for audio_info in self.input_info_list])
        # Create a list of QAudioInfo objects for outputs
        self.otput_info_list = QAudioDeviceInfo.availableDevices(
            QAudio.AudioOutput)
        if 0 == len(self.otput_info_list):
            self.otput_info_list = [QAudioDeviceInfo.defaultOutputDevice()]
        self.status_bar.showMessage(
            '{} inputs {} otputs'.format(len(self.input_info_list),
                                         len(self.otput_info_list)), 2000)
        # Create a combo box and populate it with names of outputs
        self.cb_otputs = QComboBox()
        self.cb_otputs.addItems(
            [audio_info.deviceName() for audio_info in self.otput_info_list])
        # Lay those two out aligned to the outside
        hb_combos = QHBoxLayout()
        hb_combos.addWidget(self.cb_inputs, 1)
        hb_combos.addStretch(0)
        hb_combos.addWidget(self.cb_otputs, 1)
        # Create a volume slider from 0 to 100.
        self.volume = QSlider(Qt.Horizontal, self)
        self.volume.setMinimum(0)
        self.volume.setMaximum(100)
        self.volume.setTickInterval(10)
        self.volume.setTickPosition(QSlider.TicksBothSides)
        # Create a checkbox "Mute"
        self.mute = QCheckBox('Mute')
        # Put those together in a row squeezed in the center
        hb_volume = QHBoxLayout()
        hb_volume.addStretch(1)
        hb_volume.addWidget(self.volume, 1)
        hb_volume.addWidget(self.mute, 0)
        hb_volume.addStretch(1)
        # Stack all those up as this widget's layout
        vlayout = QVBoxLayout()
        vlayout.addLayout(hb_label)
        vlayout.addLayout(hb_combos)
        vlayout.addLayout(hb_volume)
        self.setLayout(vlayout)