Detects audio level of the selected input device and displays a tray icon with the status.
PyAudio
| #!/usr/bin/python | |
| # -*- coding: utf-8 -*- | |
| import array | |
| import gtk | |
| import gobject | |
| import pyaudio | |
| class MicStatusTrayIcon(object): | |
| MUTED_ICON = gtk.STOCK_NO | |
| UNMUTED_ICON = gtk.STOCK_YES | |
| PERIOD = 1000 | |
| THRESHOLD = 100 | |
| CHUNK_SIZE = 256 | |
| FORMAT = pyaudio.paInt16 | |
| RATE = 8800 | |
| def __init__(self): | |
| self.tray = gtk.StatusIcon() | |
| self.tray.set_from_stock(self.MUTED_ICON) | |
| self.tray.connect('popup-menu', self.on_right_click) | |
| self.pyaudio = pyaudio.PyAudio() | |
| self.stream = self.pyaudio.open( | |
| format=self.FORMAT, channels=1, rate=self.RATE, input=True, | |
| frames_per_buffer=self.CHUNK_SIZE, | |
| ) | |
| # Start periodic timer | |
| self.timer_id = gobject.timeout_add(self.PERIOD, self.detect_input) | |
| def on_right_click(self, icon, event_button, event_time): | |
| menu = gtk.Menu() | |
| # About dialog | |
| about = gtk.MenuItem('About') | |
| about.show() | |
| menu.append(about) | |
| about.connect('activate', self.show_about_dialog) | |
| # Add quit item | |
| quit = gtk.MenuItem('Quit') | |
| quit.show() | |
| menu.append(quit) | |
| quit.connect('activate', self.quit) | |
| menu.popup(None, None, gtk.status_icon_position_menu, | |
| event_button, event_time, self.tray) | |
| def detect_input(self): | |
| """Record input for a while and verify if it's silent or not.""" | |
| self.stream.start_stream() | |
| snd_data = array.array('h', self.stream.read(self.CHUNK_SIZE)) | |
| self.stream.stop_stream() | |
| if max(snd_data) < self.THRESHOLD: | |
| self.tray.set_from_stock(self.MUTED_ICON) | |
| else: | |
| self.tray.set_from_stock(self.UNMUTED_ICON) | |
| return True | |
| def show_about_dialog(self, widget): | |
| """Create and show the About Dialog""" | |
| about_dialog = gtk.AboutDialog() | |
| about_dialog.set_destroy_with_parent(True) | |
| about_dialog.set_icon_name('Detect Input') | |
| about_dialog.set_name('Detect Input') | |
| about_dialog.set_version('0.1') | |
| about_dialog.set_copyright('(C) 2016 Mauricio Freitas') | |
| about_dialog.set_comments('Simple Tray Icon to show Input Status') | |
| about_dialog.set_authors(['Mauricio Freitas']) | |
| about_dialog.run() | |
| about_dialog.destroy() | |
| def quit(self, widget): | |
| self.stream.close() | |
| self.pyaudio.terminate() | |
| gtk.main_quit(widget) | |
| if __name__ == '__main__': | |
| myservice = MicStatusTrayIcon() | |
| gtk.main() |