Pasted by JockeTF at 2009-08-22, 03:48:03.
Highlight | Tree | Raw
  1. #!/usr/bin/env python
  2. "A simple volume control applet."

  3. import gtk
  4. import subprocess

  5. __author__ = "Joakim \"JockeTF\" Soderlund"
  6. __date__ = "2008-08-22"
  7. __license__ = "Public domain."

  8. # Binaries to execute.
  9. OSSMIX = "ossmix"
  10. OSSXMIX = "ossxmix"

  11. # The device to control.
  12. DEVICE = "vmix0-outvol"

  13. # The maximum outvol volume in decibels.
  14. MAX_DB = 25.0

  15. # Sets an icon for different volume levels.
  16. LEVELS = (
  17. (22, "audio-volume-high"),
  18. (18, "audio-volume-medium"),
  19. (0, "audio-volume-low"),
  20. (-1, "audio-volume-muted"),
  21. )

  22. class StatusIcon():
  23. "The status icon."
  24. def __init__(self):
  25. self.icon = gtk.StatusIcon()

  26. self.icon.connect("scroll-event", self.scrollEvent)
  27. self.icon.connect("activate", self.clickEvent)

  28. self.set_visible = self.icon.set_visible

  29. self.update()


  30. def scrollEvent(self, widget, event, *args):
  31. "Changes the volume when the user scrolls on the volume applet."
  32. if event.direction == gtk.gdk.SCROLL_UP:
  33. subprocess.call([OSSMIX, DEVICE, "--", "+%.1f" % self.getStep()])

  34. elif event.direction == gtk.gdk.SCROLL_DOWN:
  35. subprocess.call([OSSMIX, DEVICE, "--", "-%.1f" % self.getStep()])

  36. self.update()


  37. def clickEvent(self, widget, *args):
  38. "Starts or closes ossxmix when the volume applet is clicked."
  39. if not hasattr(self, "ossxmix"):
  40. self.ossxmix = subprocess.Popen([OSSXMIX, "-S"])
  41. else:
  42. if self.ossxmix.poll() == None:
  43. self.ossxmix.terminate()
  44. else:
  45. self.ossxmix = subprocess.Popen([OSSXMIX, "-S"])

  46. self.update()


  47. def getVolume(self):
  48. "Returns the current volume in decibels as a float."
  49. process = subprocess.Popen([OSSMIX, DEVICE], stdout=subprocess.PIPE)
  50. volume = float(process.communicate()[0].split()[-2])
  51. process.wait()

  52. return volume


  53. def getStep(self):
  54. "Returns the next volume step to make in decibels as a float."
  55. return (MAX_DB - self.getVolume() + 1) * 0.1


  56. def getIconName(self):
  57. "Returns the icon name for the current volume level."
  58. volume = self.getVolume()

  59. for level in LEVELS:
  60. if level[0] < volume:
  61. return level[1]


  62. def update(self, *args):
  63. "Updates the volume applet's tooltip and icon."
  64. self.icon.set_tooltip("Volume: %.1f dB" % self.getVolume())
  65. self.icon.set_from_icon_name(self.getIconName())


  66. if __name__ == "__main__":
  67. icon = StatusIcon()
  68. icon.set_visible(True)

  69. try:
  70. gtk.main()
  71. except KeyboardInterrupt:
  72. print("")