Esempio n. 1
0
    def getMixer(self):
        i=0
        selected=0
        for z in reversed(alsaaudio.card_indexes()):
            card = pulse.card_list()[i]
            (name, longname) = alsaaudio.card_name(z)
            if name == self.soundcards.currentText():
                #pulse.card_profile_set(card, card.profile_list[self.selectedProfile])
                self.selectedCard = card
                selected = z
            else:
                pulse.card_profile_set(card, 'off')
            i=i+1

        self.cardmixer.clear()
        current = 0
        i = 0
        for name in alsaaudio.mixers(selected):
            #print("  '%s'" % name)
            if self.settings["mixer"] == name:
                current=i
                self.parent.volume.setMixer(name)
            self.cardmixer.addItem(name)
            i=i+1
        self.cardmixer.setCurrentIndex(current)
        self.getProfile()
Esempio n. 2
0
def list_cards():
    cards.clear()
    count = 0
    for i in alsaaudio.card_indexes():
        (name, longname) = alsaaudio.card_name(i)
        cards[count] = longname
        count = count + 1
Esempio n. 3
0
def find_devices():
    """
    Used to determine the device node of the different devices, and the alsa devices for the audio.
    Returns:
        Dictionary, with the being the name of the device, and the value a list of ["/dev/videoX", "usb-id", "alsa-index"].
            This is the device node, the USB-id and the related alsa audio device index.
    """
    res = subprocess.run(
        ["v4l2-ctl", "--list-devices"], stdout=subprocess.PIPE, universal_newlines=True
    )
    # output has the form:
    # 'Cam Link 4K (usb-70090000.xusb-1.4):'
    # '   /dev/video0'
    cleaned = [x for x in res.stdout.split("\n") if x != ""]
    audio_devices = {x: alsaaudio.card_name(x) for x in alsaaudio.card_indexes()}
    devices = {}
    for idx in range(0, len(cleaned), 2):
        dev = cleaned[idx + 1][1:]
        name, usb = cleaned[idx][:-2].split(" (usb-")
        usb = "usb-" + usb
        audio_idx = -1
        for k, v in audio_devices.items():
            if name in v:
                audio_idx = k
        devices[name] = [dev, usb, audio_idx]
    return devices
Esempio n. 4
0
    def get_sound_cards():
        soundcards = {}
        for i in alsaaudio.card_indexes():
            if 'PCM' in alsaaudio.mixers(**{'cardindex': i}):
                (name, longname) = alsaaudio.card_name(i)
                soundcards[name] = {'hwid': int(i), 'name': longname}

        return soundcards
Esempio n. 5
0
 def testMixer(self):
     """Open the default Mixers and the Mixers on every card"""
     
     for c in alsaaudio.card_indexes():
         mixers = alsaaudio.mixers(cardindex=c)
         
         for m in mixers:
             mixer = alsaaudio.Mixer(m, cardindex=c)
             mixer.close()
Esempio n. 6
0
 def _get_alsa_mixers():
     """
     Returns all alsa mixers
     :return: dict, alsa mixers
     """
     mixers = {}
     ind = alsaaudio.card_indexes()
     for i in range(0, len(ind)):
         mix = alsaaudio.Mixer(control=alsaaudio.mixers(i)[0], id=0, cardindex=ind[i])
         mixers.update({mix.cardname(): mix})
     return mixers
Esempio n. 7
0
  def get_sound_cards():
    soundcards = {}
    for i in alsaaudio.card_indexes():
      try:
        (name, longname) = alsaaudio.card_name(i)
        soundcards[name] = {'hwid' : int(i), 'name' : longname}

      except Exception as ex:
        # Just ignore error, and skip it
        pass

    return soundcards
Esempio n. 8
0
    def available_soundcards(__cls__):
        soundcards = []
        for i in alsaaudio.card_indexes():
            try:
                (name, longname) = alsaaudio.card_name(i)
                soundcards.append({'index': int(i), 'name': longname})

            except Exception as ex:
                # Just ignore error, and skip it
                pass

        return soundcards
Esempio n. 9
0
 def getSoundcards(self):
     current = 0
     i=0
     for z in reversed(alsaaudio.card_indexes()):
         (name, longname) = alsaaudio.card_name(i)
         #print("  %d: %s (%s)" % (i, name, longname))
         self.soundcards.addItem(name, z)
         if self.settings["card"] == name:
             current=i
         i=i+1
     self.soundcards.setCurrentIndex(current)
     self.getMixer()
Esempio n. 10
0
 def _get_mixers(self):
     """
     Get all alsa mixers available and give them a name.
     :return: dict, {mixer1.name: mixer1, ... }
     """
     mixers = {}
     ind = alsaaudio.card_indexes()
     for i in range(0, len(ind)):
         mix = alsaaudio.Mixer(control=alsaaudio.mixers(i)[0],
                               id=0,
                               cardindex=ind[i])
         mixer = Mixer(mix, self._config)
         mixers.update({mixer.name: mixer})
     return mixers
Esempio n. 11
0
 def getProfile(self):
     self.cardprofile.clear()
     i=0
     for z in reversed(alsaaudio.card_indexes()):
         card = pulse.card_list()[i]
         (name, longname) = alsaaudio.card_name(z)
         if name == self.soundcards.currentText():
             index = 0
             for profile in card.profile_list:
                 self.cardprofile.addItem(profile.description)
                 if profile.description == self.settings["profile"]:
                     pulse.card_profile_set(self.selectedCard, self.selectedCard.profile_list[index])
                     self.selectedProfile = index
                 index = index+1
         i=i+1
     self.cardprofile.setCurrentIndex(self.selectedProfile)
Esempio n. 12
0
 def __init__(self):
     self.mixerid = ''
     self.cardindex = None
     for ci in alsaaudio.card_indexes():
         if "seeed" in alsaaudio.cards()[ci]:
             self.cardindex = ci
     if self.cardindex is None:
         # We don't run a seeed card, use the default mixer
         self.cardindex = 0
         self.mixerid = alsaaudio.mixers(self.cardindex)[0]
     else:
         for i in alsaaudio.mixers(self.cardindex):
             if i == 'Master' or i == 'PCM' or i == 'Speaker' or i == 'Playback':
                 self.mixerid = i
         if self.mixerid == '':
             raise Exception('Cannot find mixer')
     self.mixer = alsaaudio.Mixer(cardindex=self.cardindex,
                                  control=self.mixerid)
Esempio n. 13
0
 def update_card_lists(self):
     """ """
     self.clear()
     # List cards and names.
     # Note: Results from card_indexes() and cards() must be mapped.
     card_ids = alsaaudio.cards()
     for id_index, card_index in enumerate(alsaaudio.card_indexes()):
         card_dict = {}
         card_dict["card_index"] = card_index
         card_dict["card_id"] = card_ids[id_index]
         card_name, long_name = alsaaudio.card_name(card_index)
         card_dict["card_name"] = card_name.strip()
         card_dict["card_long_name"] = long_name.strip()
         self.card_list.append(card_dict)
     # Check card devices for capture.
     for device in alsaaudio.pcms(alsaaudio.PCM_CAPTURE):
         if device.startswith("sysdefault:CARD="):
             card_id = device.replace("sysdefault:CARD=", "").strip()
             for card_dict in self.card_list:
                 if card_dict.get("card_id", "") == card_id:
                     card_dict["device"] = device
                     card_index = card_dict.get("card_index", "")
                     if card_index != "":
                         self.capture_card_index_list.append(card_index)
     # Check card devices for playback.
     for device in alsaaudio.pcms(alsaaudio.PCM_PLAYBACK):
         if device.startswith("sysdefault:CARD="):
             card_id = device.replace("sysdefault:CARD=", "").strip()
             for card_dict in self.card_list:
                 if card_dict.get("card_id", "") == card_id:
                     card_dict["device"] = device
                     card_index = card_dict.get("card_index", "")
                     if card_index != "":
                         self.playback_card_index_list.append(card_index)
     # For debug.
     for card_dict in self.card_list:
         card_name = card_dict.get("card_name", "")
         card_index = card_dict.get("card_index", "")
         self.logger.debug("Sound card: " + card_name + "   Index: " +
                           str(card_index))
     self.logger.debug("Sound cards capture: " +
                       str(self.capture_card_index_list))
     self.logger.debug("Sound cards playback: " +
                       str(self.playback_card_index_list))
Esempio n. 14
0
 def run(self):
     while threading.main_thread().is_alive():
         for dev in hal.Devices.Modules:
             if isinstance(dev, ALSAAudio):
                 dev.Found = False
         try:
             for i in alsaaudio.card_indexes():
                 (name, longname) = alsaaudio.card_name(i)
                 if hal.Devices.find(name) == None:
                     ALSAAudio(name, "hw:" + str(i))
                 else:
                     hal.Devices.find(name, ALSAAudio).Found = True
         except:
             pass
         for dev in hal.Devices.Modules:
             if isinstance(dev, ALSAAudio):
                 if dev.Found == False:
                     #print("deleting "+dev._id)
                     del (dev)
         time.sleep(0.3)
     return
Esempio n. 15
0
def list_cards():
    print("Available sound cards:")
    for i in alsaaudio.card_indexes():
        (name, longname) = alsaaudio.card_name(i)
        print("  %d: %s (%s)" % (i, name, longname))
Esempio n. 16
0
    def testPCM(self):
        "Open a PCM object on every card"

        for c in alsaaudio.card_indexes():
            pcm = alsaaudio.PCM(cardindex=c)
            pcm.close()
Esempio n. 17
0
    def scan(self, override_params=None, quiet=False):

        if override_params is not None: self.params = override_params

        # Check device is present on the bus.
        if 'bcdDevice' in self.params.keys():
            usbCoreDev = usb.core.find(idVendor=self.params['vid'],idProduct=self.params['pid'],\
                             bcdDevice=self.params['bcdDevice'])
        else:
            usbCoreDev = usb.core.find(idVendor=self.params['vid'],
                                       idProduct=self.params['pid'])

        if usbCoreDev is None:
            raise pyLabDataLoggerIOError("USB Device %s not found" %
                                         self.params['name'])

        #print usbCoreDev.bus, usbCoreDev.address

        if self.alsacard is not None:
            if not self.alsacard in alsaaudio.card_indexes():
                raise IndexError("Invalid ALSA card number requested.")
        else:

            # Scan ALSA devices
            if 'card_indexes' in dir(alsaaudio):
                cards = [(n, ' '.join(alsaaudio.card_name(n)))
                         for n in alsaaudio.card_indexes()]
            elif 'cards' in dir(alsaaudio):
                cards = [(n, alsaaudio.cards()[n])
                         for n in range(len(alsaaudio.cards()))]
            else:
                raise RuntimeError("Unknown alsaaudio API:\n" + dir(alsaaudio))
            #if self.debugMode: print "\tAll ALSA devices:",alsaaudio.cards()

            #  find one that matches the USB device found.
            if any([
                    'USB' in c[1] for c in cards
            ]):  # if 'USB' in the name of any device, select from those
                cards = [c for c in cards if 'USB' in c[1]]
            if len(cards) == 0:
                cprint("\tUnable to find a USB ALSA device.",
                       'red',
                       attrs=['bold'])
                # abort setup.
                return
            elif len(cards) == 1:
                cprint("\tFound 1 USB ALSA card: [card %02i] %s" % cards[0],
                       'green')
                self.alsacard = cards[0][0]
                self.name = "ALSA Audio device " + cards[0][1]
            elif len(cards) > 1:
                print(
                    "\tFound multiple ALSA cards. The first one may be your internet sound card."
                )
                print("\tPlease choose one of:")
                for j in range(len(cards)):
                    print("\t\t%i: [card %02i] %s" %
                          (j, cards[j][0], cards[j][1]))
                j = -1
                while (j < 0) or (j >= len(cards)):
                    try:
                        j = int(
                            input("Choose audio stream [0-%i]:" %
                                  (len(cards) - 1)))
                    except KeyboardInterrupt:
                        exit(1)
                    except:
                        pass
                self.alsacard = cards[j][0]
                self.name = "ALSA Audio device " + cards[j][1]

        if self.alsacard: self.activate(quiet=quiet)
        return
Esempio n. 18
0
# short example how to use integriot and alsaaudio to control the volume via mqtt
# author: ulno

# TODO: turn these into arguments
mqtt_server = "homeaut"
sink_name = 'Altec Lansing XT2 - USB Audio'
location = "living-room"
device = "audio01/volume"

import alsaaudio  # https://pypi.org/project/pyalsaaudio/
from integriot import *
from time import sleep

# find card
card = -1
for index in alsaaudio.card_indexes():
    if sink_name in alsaaudio.card_name(index):
        card = index
        break
mixers = alsaaudio.mixers(cardindex=card)
sink = None
for name in ["Master", "PCM", "Speaker", "Front", "FM"]:
    if name in mixers:
        sink = alsaaudio.Mixer(name, cardindex=card)
        break

if sink is None:
    print("Mixer not found")
    exit(1)

# mqtt setup