Esempio n. 1
0
    def get_alsa_mixers(self, cardid = 0, mixerid = None):
        if config.disable_alsa:
            return []

        if cardid < len(alsaaudio.cards()):
            if mixerid == None:
                return alsaaudio.mixers(cardid)

            elif mixerid < len(alsaaudio.mixers(cardid)):
                return alsaaudio.mixers(cardid)[mixerid]
Esempio n. 2
0
    def is_alsa_device(self, device_name):
        print 'MIXERS: %s' % alsaaudio.mixers()  #show available mixer controls

        if gv.IS_DEBIAN == False:
            return

        if device_name == 'bcm2835':
            mixer_card_index = 0
        else:
            mixer_card_index = re.search(
                '\(hw:(.*),',
                device_name)  # get x from (hw:x,y) in device name
            print mixer_card_index
            if mixer_card_index == None:
                mixer_card_index = 0
            else:
                mixer_card_index = int(mixer_card_index.group(1))

        available_mixer_types = alsaaudio.mixers(
        )  # returns a list of available mixer types. Usually only "PCM"
        print "YAO CHUN LIN"
        print available_mixer_types

        for mixer_control in available_mixer_types:
            print '>>>> Trying mixer control "%s"' % mixer_control
            for mixer_id in range(0, 6):
                try:
                    if self.alib == 1 or 'A2DP' in mixer_control:
                        amixer = alsaaudio.Mixer(control=mixer_control)
                    else:
                        amixer = alsaaudio.Mixer(id=mixer_id,
                                                 cardindex=mixer_card_index,
                                                 control=mixer_control)
                    print amixer.cardname()
                    del amixer  # No use for amixer in this method. Create instance in start_alsa_mixer()
                    gv.USE_ALSA_MIXER = True
                    self.mixer_id = mixer_id
                    self.mixer_card_index = mixer_card_index  # save the found value
                    self.mixer_control = mixer_control
                    print '>>>> Found ALSA device: card id "%i", control "%s"' % (
                        self.mixer_card_index, mixer_control)

                    return True

                except Exception as e:
                    # gv.displayer.disp_change('Invalid mixerdev', line=2, timeout=0)
                    # print 'Invalid mixer card id "%i" or control "%s"' % (gv.MIXER_CARD_ID, gv.MIXER_CONTROL)
                    print 'Invalid mixer card id "%i" or control "%s"' % (
                        mixer_card_index, mixer_control)
                    # print 'Available devices (mixer card id is "x" in "(hw:x,y)" of device #%i):' % gv.AUDIO_DEVICE_ID
                    # print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e), e)

        print '>>>> This is not an ALSA compatible device'
        gv.USE_ALSA_MIXER = False
        return False
Esempio n. 3
0
    def __init__(self):
        super().__init__()

        all_mixers_list = alsaaudio.mixers()
        self.__out = find_mixer(["Master", "PCM", "Speaker"], all_mixers_list)
        self.__out.setvolume(MainLoader.get("MIXER_OUT", 100))

        self.__in = find_mixer(["Mic"], all_mixers_list)
        self.__in.setvolume(MainLoader.get("MIXER_IN", 50))

        assert always_true("Found mixers:", alsaaudio.mixers(), str(self))
Esempio n. 4
0
def get_mixer_name():
    """

    :return: Mixer name : either the one in config.py, or if it doesn't exist the first in the list of available mixers
    """
    if "AMIXER_CHANNEL" in app.config and app.config[
            "AMIXER_CHANNEL"] in alsaaudio.mixers():
        return app.config["AMIXER_CHANNEL"]
    else:
        # app.logger.info(alsaaudio.mixers())
        return alsaaudio.mixers()[0]
Esempio n. 5
0
    def _read_config(self):
        self.soundcard_name = g15gconf.get_string_or_default(self._gconf_client, \
                                                             self._gconf_key + "/soundcard", \
                                                             str(alsaaudio.cards()[0]))
        self.soundcard_index = alsaaudio.cards().index(self.soundcard_name)

        self.mixer_name = g15gconf.get_string_or_default(self._gconf_client, \
                                                         self._gconf_key + "/mixer", \
                                                         str(alsaaudio.mixers(self.soundcard_index)[0]))
        if not self.mixer_name in alsaaudio.mixers(self.soundcard_index):
            self.mixer_name = str(alsaaudio.mixers(self.soundcard_index)[0])
            self._gconf_client.set_string(self._gconf_key + "/mixer", self.mixer_name)
Esempio n. 6
0
def mic_loop():
    # constants
    samplerate = 44100
    win_s = 2048
    hop_s = win_s // 2
    framesize = hop_s

    print alsaaudio.cards()
    print alsaaudio.mixers()
    # set up audio input
    recorder = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE)
    #recorder = alsaaudio.PCM(type=PCM_CAPTURE, cardindex=1)
    recorder.setperiodsize(framesize)
    recorder.setrate(samplerate)
    #recorder.setformat(alsaaudio.PCM_FORMAT_FLOAT_LE)
    recorder.setchannels(1)

    # create aubio pitch detection (first argument is method, "default" is
    # "yinfft", can also be "yin", "mcomb", fcomb", "schmitt").
    pitcher = aubio.pitch("default", win_s, hop_s, samplerate)
    # set output unit (can be 'midi', 'cent', 'Hz', ...)
    pitcher.set_unit("Hz")
    # ignore frames under this level (dB)
    pitcher.set_silence(-40)

    print("Starting to listen, press Ctrl+C to stop")

    count = 0
    # main loop
    while True:
        #    try:
        # read data from audio input
        _, data = recorder.read()
        # convert data to aubio float samples
        #samples = np.fromstring(data, dtype=aubio.float_type)
        samples = np.fromstring(data, dtype=np.int16)
        #print(len(samples),samples.min(),samples.max())
        # pitch of current frame
        #sample_test = np.hstack((samples,samples))
        sample_test = np.array(samples, dtype=np.float32)
        freq = pitcher(sample_test)[0]
        # compute energy of current block
        energy = np.sum(sample_test**2) / len(sample_test)
        # do something with the results
        if freq > 130 and freq < 200 and energy > 200000:
            count = count + 1
        if count > 1:
            count = 0
            people = 1
            print("{:10.4f} {:10.4f}".format(freq, energy))
        else:
            people = 0
Esempio n. 7
0
 def get_cards(self):
     """ Returns cards list """
     cards = []
     acards = alsa.cards()
     for index, card in enumerate(acards):
         try:
             alsa.mixers(index)[0]
         except Exception, err:
             # card doesn't have any mixer control
             cards.append(None)
             print str(err)
         else:
             cards.append(acards[index])
Esempio n. 8
0
    def __init__(self, gpio, config):
        self.gpio = gpio
        try:
            if len(alsaaudio.mixers()) > 0:
                self.mixer = alsaaudio.Mixer(alsaaudio.mixers()[0])
            else:
                self.mixer = None
        except alsaaudio.ALSAAudioError:
            self.mixer = None

        volumeSteps = json.loads(config['AUDIO']['VolumeSteps'])
        self.volumeMap = dict(map(lambda item: (int(item[0]), item[1]), volumeSteps.items()))
        self.reverseVolumeMap = dict(map(lambda item: (item[1], int(item[0])), volumeSteps.items()))
Esempio n. 9
0
    def _read_config(self):
        self.soundcard_name = g15gconf.get_string_or_default(self._gconf_client, \
                                                             self._gconf_key + "/soundcard", \
                                                             str(alsaaudio.cards()[0]))
        self.soundcard_index = alsaaudio.cards().index(self.soundcard_name)

        self.mixer_name = g15gconf.get_string_or_default(self._gconf_client, \
                                                         self._gconf_key + "/mixer", \
                                                         str(alsaaudio.mixers(self.soundcard_index)[0]))
        if not self.mixer_name in alsaaudio.mixers(self.soundcard_index):
            self.mixer_name = str(alsaaudio.mixers(self.soundcard_index)[0])
            self._gconf_client.set_string(self._gconf_key + "/mixer",
                                          self.mixer_name)
Esempio n. 10
0
 def get_cards(self):
     """ Returns cards list """
     cards = []
     acards = alsa.cards()
     for index, card in enumerate(acards):
         try:
             alsa.mixers(index)[0]
         except Exception, err:
             # card doesn't have any mixer control
             cards.append(None)
             print str(err)
         else:
             cards.append(acards[index])
Esempio n. 11
0
 def SetOutputVolume(self, Volume, channel=None):
     if 'PCM' in alsaaudio.mixers(device=self.hw):
         mixer = alsaaudio.Mixer('PCM', device=self.hw)
     elif 'Speaker' in alsaaudio.mixers(device=self.hw):
         mixer = alsaaudio.Mixer('Speaker', device=self.hw)
     else:
         return False
     vols = mixer.getvolume(alsaaudio.PCM_PLAYBACK)
     if channel is None:
         for i in range(len(vols)):
             mixer.setvolume(Volume, i)
     else:
         mixer.setvolume(Volume, channel)
     return True
Esempio n. 12
0
    def __init__(self, start_vol, vol_inc, clk, dt, btn, rot_type):
        cardId = 0

        self.startvol = start_vol
        self.volinc = vol_inc
        self.hasMute = True  # Are we using the Digital control or the SoftMaster
        self.isMute = False
        self.clk = clk  # First rotary pin
        self.dt = dt  # Second rotary pin
        self.btn = btn  # Button pin
        self.rotary = None

        # Is the rotary encoder keyes like i.e. pull down or standard i.e. pull up
        if rot_type in ROTARY_TYPES:
            self.rot_type = rot_type
            print("Configuring rotary encoder as ", self.rot_type)
        else:
            print(rot_type, " is not a valid rotary encoder type")
            exit()

        # Finds the JustBoom card
        for i in range(len(alsaaudio.cards())):
            print(alsaaudio.cards()[i])
            if (alsaaudio.cards()[i] == 'sndrpiboomberry'
                    or alsaaudio.cards()[i] == 'sndrpijustboomd'):
                cardId = i
                if 'Digital' in alsaaudio.mixers(cardId):
                    self.mixer = alsaaudio.Mixer(control='Digital',
                                                 cardindex=cardId)
                    self.hasMute = True
                elif 'SoftMaster' in alsaaudio.mixers(cardId):
                    self.mixer = alsaaudio.Mixer(control='SoftMaster',
                                                 cardindex=cardId)
                    self.hasMute = False
                else:
                    print("There are no suitable mixers")
                    exit()
                self.rotary = Rotary(self.clk, self.dt, self.btn,
                                     self.rotarychange, self.buttonpressed,
                                     self.rot_type)
        if self.rotary == None:
            print("There are no suitable cards")
            exit()

        # Init the mqtt stuff
        super().__init__()
        self.connect(MQTT_HOST, MQTT_PORT, 60)
        # With the # suffix we subscribe to all subtopics
        self.subscribe(MQTT_COMMAND_TOPICS + "#")
Esempio n. 13
0
    def __init__(self):
        os.putenv(
            'SDL_FBDEV',
            '/dev/fb1')  # Route the output to framebuffer 1 (TFT display)
        pygame.init()
        pygame.font.init()
        self.lcd = pygame.display.set_mode((320, 240))
        pygame.mouse.set_visible(False)
        pygame.key.set_repeat(500, 100)
        self.dispWidth, self.dispHeight = pygame.display.get_surface(
        ).get_size()

        self.font = pygame.font.Font("TerminusTTF-4.46.0.ttf", 18)
        pygame.mixer.init()
        pygame.mixer.music.set_volume(1.0)
        self.alsa = alsaaudio.Mixer(alsaaudio.mixers()[0])
        self.alsa.setvolume(self.volume)

        # Load music
        self.load()

        # Initialize ADC
        self.adc = Adafruit_ADS1x15.ADS1115()

        # Set backlight pin as output and turn it on
        GPIO.setwarnings(
            False
        )  # disable warning because it is known that the pin is already set as output
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(23, GPIO.OUT)
        GPIO.output(23, GPIO.HIGH)
Esempio n. 14
0
    def __init__(self, parent=None, cp=None, card_index=0):
        gtk.Window.__init__(self)
        self.connect('destroy', self.close)
        self.set_title('Select Controls')
        self.set_transient_for(parent)
        self.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
        self.set_border_width(10)
        self.set_default_size(200, 300)

        icon_theme = gtk.icon_theme_get_default()
        self.set_icon_name("preferences-desktop")

        self.cp = cp
        self.main = parent
        self.card_index = card_index
        self.mixers = alsa.mixers(self.card_index)

        try:
            self.main.control_mask[self.card_index] = int(
                self.cp.get("card-%d" % self.card_index, "mask_control"))
        except:
            self.main.control_mask[self.card_index] = 0
            for count, mixer in enumerate(self.mixers):
                self.main.control_mask[self.card_index] |= (1 << count)

        self.set_layout()
Esempio n. 15
0
    def __init__(self, reverse, card, maxvol, vicons):
        self.REVERSE_SCROLL = reverse
        self.CARD = card
        self.MAX_VOLUME = maxvol
        self.VOLATILE_ICONS = vicons

        self.MASTER = alsaaudio.mixers(self.CARD)[0]

        self.PANEL_HEIGHT = 34  # in pixels, negative if panel is on bottom
        self.WINDOW_OPACITY = 0.95  #
        self.VOLUME_WIDTH = 200  # in pixels
        self.VOLUME_HEIGHT = 25  # in pixels, adjust if the widget doesn't fit
        self.SCROLL_BY = 3  # increase to scroll "faster"

        self.VOLUME_MULTIPLIER = float(100) / self.MAX_VOLUME

        if self.REVERSE_SCROLL:
            self.SCROLL_BY *= -1

        self.init_gtk()
        self.init_alsa()

        self.update()
        self.icon.set_visible(True)

        signal.signal(signal.SIGINT, gtk.main_quit)
        gtk.main()
Esempio n. 16
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. 17
0
def set_volume(volume, pcm_type, nonlinear=False):
    """Change the mixer volume.

    Parameters
    ----------
    volume : float
        New value between 0 and 1
    pcm_type : int
        0 for output (PCM_PLAYBACK), 1 for input (PCM_CAPTURE)
    nonlinear : bool
        if True, will apply to_mixer_volume
    """
    if pcm_type == alsaaudio.PCM_PLAYBACK:
        mixer_name = OUTPUT_VOLUME
    elif pcm_type == alsaaudio.PCM_CAPTURE:
        mixer_name = INPUT_VOLUME
    else:
        raise ValueError(f'Unsupported PCM {pcm_type}')

    if mixer_name not in alsaaudio.mixers():
        logger.error('Could not find mixer %s', mixer_name)
        return

    if nonlinear:
        volume = to_mixer_volume(volume)

    mixer_volume = min(100, max(0, round(volume * 100)))

    mixer = alsaaudio.Mixer(mixer_name)

    current_mixer_volume = mixer.getvolume(pcm_type)[0]
    if mixer_volume == current_mixer_volume:
        return

    mixer.setvolume(mixer_volume)
Esempio n. 18
0
    def __init__(self, config):
        super().__init__()
        self.config = config
        self.cardindex = self.config["alsamixer"]["card"]
        self.control = self.config["alsamixer"]["control"]
        self.min_volume = self.config["alsamixer"]["min_volume"]
        self.max_volume = self.config["alsamixer"]["max_volume"]
        self.volume_scale = self.config["alsamixer"]["volume_scale"]

        known_cards = alsaaudio.cards()
        try:
            known_controls = alsaaudio.mixers(self.cardindex)
        except alsaaudio.ALSAAudioError:
            raise exceptions.MixerError(
                f"Could not find ALSA soundcard with index {self.cardindex:d}. "
                "Known soundcards include: "
                f"{', '.join(known_cards)}"
            )

        if self.control not in known_controls:
            raise exceptions.MixerError(
                f"Could not find ALSA mixer control {self.control} on "
                f"card {self.cardindex:d}. "
                f"Known mixers on card {self.cardindex:d} include: "
                f"{', '.join(known_controls)}"
            )

        self._last_volume = None
        self._last_mute = None

        logger.info(
            f"Mixing using ALSA, card {self.cardindex:d}, "
            f"mixer control {self.control!r}."
        )
Esempio n. 19
0
    def __init__(self):
        cards = aa.cards()
        scarlett_index = None
        for i in range(0, len(cards)):
            if cards[i] == "USB":
                # it's probably scarlett
                scarlett_index = i
        if not scarlett_index:
            raise Exception("Couldn't find your scarlett usb device!")
        else:
            print "Found Scarlett at index {}".format(scarlett_index)

        scarlett_mixers = aa.mixers(scarlett_index)

        print "Found {} scarlett mixers".format(len(scarlett_mixers))
        matricies, matrix_inputs, masters = unpackMixers(
            scarlett_mixers, scarlett_index)
        self.input_channels = []
        for i in range(0, len(matricies)):
            self.input_channels.append(
                ScarlettInputChannel(matricies[i], matrix_inputs[i]))
        self.loadPolls()
        self.master_mixers = []
        for output in masters:
            input_controller = None
            lr_mixers = {}
            for con in masters[output]:
                if len(masters[output][con].getenum()) == 0:
                    input_controller = masters[output][con]
                else:
                    lr_mixers[con] = masters[output][con]
            self.master_mixers.append(
                ScarlettInputChannel(lr_mixers, input_controller))
Esempio n. 20
0
 def init_device(self):
     device = None
     for i, card in enumerate(alsaaudio.cards()):
       if VOL_CTRL in alsaaudio.mixers(i):
         device = i
         break
     self.device = device
Esempio n. 21
0
 def init_device(self):
     device = None
     for i, card in enumerate(alsaaudio.cards()):
         if VOL_CTRL in alsaaudio.mixers(i):
             device = i
             break
     self.device = device
Esempio n. 22
0
def ls_cards_mixers():
    """ List the availaible cards and mixers.

    List all the available cards and all the usable mixers of each cards.
    """
    global CARD_LIST
    global MIXER_LIST
    CARD_LIST = alsaaudio.cards()
    for card_name in CARD_LIST:
        MIXER_LIST[card_name] = {
            'pretty_name':
            "%s (hw:%i)" % (card_name, CARD_LIST.index(card_name)),
            'mixers': [],
        }
        try:
            for mixer_name in alsaaudio.mixers(CARD_LIST.index(card_name)):
                mixer = alsaaudio.Mixer(control=mixer_name,
                                        cardindex=CARD_LIST.index(card_name))
                if len(mixer.volumecap()) > 0 and mixer.volumecap()[0] in \
                    ("Volume", "Playback Volume", "Joined Playback Volume"):
                    try:
                        mixer.getvolume()
                    except alsaaudio.ALSAAudioError:
                        pass
                    else:
                        MIXER_LIST[card_name]['mixers'].append(mixer_name)
        except alsaaudio.ALSAAudioError:
            pass
Esempio n. 23
0
def get_controls(driver, device):
    """Return a list of available controls on the device"""
    if driver not in available_drivers:
        raise MixerError("Invalid driver: '{0}'".format(str(driver)))
    if driver == "ALSA":
        # Convert device to index
        dev = _alsa_device_to_idx(device)
        # Filter out the controls that can't control the volume
        valid = []
        for c in alsaaudio.mixers():
            try:
                m = alsaaudio.Mixer(c, cardindex=dev)
                if len(m.volumecap()) > 0:
                    valid.append(c)
                m.close()
            except alsaaudio.ALSAAudioError:
                pass
    elif driver == "OSS":
        try:
            om = ossaudiodev.openmixer(device)
        except (IOError, ossaudiodev.OSSAudioError) as oe:
            raise MixerError("Error opening mixer: {0}".format(str(oe)))
        bitmask = om.controls()
        om.close()
        # Filter out unavailable controls
        valid = [ossaudiodev.control_labels[c].rstrip() for
                 c in range(len(ossaudiodev.control_labels))
                 if bitmask & (1 << c)]
    if len(valid) < 1:
        raise MixerError("Could not find any controls for {0}".format(device))
    else:
        return valid
Esempio n. 24
0
 def default_control():
     mixers = alsaaudio.mixers()
     if len(mixers) > 0:
         control = mixers.pop(0)
     else:
         control = 'Mixer'
     return control
Esempio n. 25
0
    def __init__(self, config):
        super(AlsaMixer, self).__init__()
        self.config = config
        self.card = self.config['alsamixer']['card']
        self.control = self.config['alsamixer']['control']

        known_cards = alsaaudio.cards()
        if self.card >= len(known_cards):
            raise exceptions.MixerError(
                'Could not find ALSA soundcard with index %(card)d. '
                'Known soundcards include: %(known_cards)s' % {
                    'card':
                    self.card,
                    'known_cards':
                    ', '.join('%d (%s)' % (i, name)
                              for i, name in enumerate(known_cards)),
                })

        known_controls = alsaaudio.mixers(self.card)
        if self.control not in known_controls:
            raise exceptions.MixerError(
                'Could not find ALSA mixer control %(control)s on '
                'card %(card)d. Known mixers on card %(card)d include: '
                '%(known_controls)s' % {
                    'control': self.control,
                    'card': self.card,
                    'known_controls': ', '.join(known_controls),
                })

        self._last_volume = None
        self._last_mute = None

        logger.info('Mixing using ALSA, card %d, mixer control "%s".',
                    self.card, self.control)
Esempio n. 26
0
    def __init__(self, parent=None, cp=None, card_index=0):
        GObject.GObject.__init__(self)
        self.connect('destroy', self.close)
        self.set_title('Select Controls')
        self.set_transient_for(parent)
        self.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
        self.set_border_width(10)
        self.set_default_size(200, 300)

        icon_theme = Gtk.IconTheme.get_default()
        self.set_icon_name("preferences-desktop")

        self.cp = cp
        self.main = parent
        self.card_index = card_index
        self.mixers = alsa.mixers(self.card_index)

        try:
            self.main.control_mask[self.card_index] = int(
                    self.cp.get("card-%d" % self.card_index, "mask_control"))
        except:
            self.main.control_mask[self.card_index] = 0
            for count, mixer in enumerate(self.mixers):
                self.main.control_mask[self.card_index] |= (1 << count)

        self.set_layout()
Esempio n. 27
0
def get_volume(pcm, nonlinear=False):
    """Get the current mixer volume between 0 and 1.

    Parameters
    ----------
    pcm : int
        0 for output (PCM_PLAYBACK), 1 for input (PCM_CAPTURE)
    nonlinear : bool
        if True, will apply to_perceived_volume
    """
    if pcm == alsaaudio.PCM_PLAYBACK:
        mixer_name = OUTPUT_VOLUME
    elif pcm == alsaaudio.PCM_CAPTURE:
        mixer_name = INPUT_VOLUME
    else:
        raise ValueError(f'Unsupported PCM {pcm}')

    if mixer_name not in alsaaudio.mixers():
        logger.error('Could not find mixer %s', mixer_name)
        # might be due to configuration
        return 100

    mixer = alsaaudio.Mixer(mixer_name)
    mixer_volume = mixer.getvolume(pcm)[0] / 100

    if nonlinear:
        return to_perceived_volume(mixer_volume)

    return mixer_volume
Esempio n. 28
0
    def test_set_volume(self):
        nameOfMixer = alsaaudio.mixers()[0]

        assert (self.audioInstance.set_volume(0) == True)
        mixer = alsaaudio.Mixer(nameOfMixer)
        assert (mixer.getvolume() == [0, 0])

        assert (self.audioInstance.set_volume(25) == True)
        mixer = alsaaudio.Mixer(nameOfMixer)
        assert (mixer.getvolume() == [25, 25])

        assert (self.audioInstance.set_volume(50) == True)
        mixer = alsaaudio.Mixer(nameOfMixer)
        assert (mixer.getvolume() == [50, 50])

        assert (self.audioInstance.set_volume(100) == True)
        mixer = alsaaudio.Mixer(nameOfMixer)
        assert (mixer.getvolume() == [100, 100])

        assert (self.audioInstance.set_volume(101) == False)
        mixer = alsaaudio.Mixer(nameOfMixer)
        assert (mixer.getvolume() == [100, 100])

        assert (self.audioInstance.set_volume(-1) == False)
        mixer = alsaaudio.Mixer(nameOfMixer)
        assert (mixer.getvolume() == [100, 100])

        # To prevent my ears from being blasted after running the test suite
        assert (self.audioInstance.set_volume(35) == True)
Esempio n. 29
0
def set_mute(mixer_name, state):
    """Set if the mixer should be muted or not."""
    if mixer_name not in alsaaudio.mixers():
        logger.error('Could not find mixer %s', mixer_name)
        return
    mixer = alsaaudio.Mixer(mixer_name)
    mixer.setmute(state)
Esempio n. 30
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. 31
0
 def __init__(self):
     self._osd = OSDPercentage(font=FONT, colour="#6a5acd", timeout=3) # slate blue
     kn = self._knob = PowerVolume()
     kn.open()
     kn.register_motion(self.change_volume)
     kn.register_button(self.handle_button)
     am = self._mixer = alsaaudio.Mixer(alsaaudio.mixers()[0]) # XXX
     self._volume = am.getvolume()[0]
Esempio n. 32
0
 def _list_mixers():
     num_cards = len(alsaaudio.cards())
     for card in range(num_cards):
         for mixername in alsaaudio.mixers(card):
             mixer = alsaaudio.Mixer(control=mixername, cardindex=card)
             if "Capture Mute" not in mixer.switchcap():
                 continue
             yield (card, mixername)
Esempio n. 33
0
 def get_mixers(cardindex = 0):
     '''
     Get the names of all available mixers for an audio card
     
     @param   cardindex:int  The index of the audio card
     @return  :list<str>     The names of all available mixers for an audio card
     '''
     return alsaaudio.mixers(cardindex)
Esempio n. 34
0
 def __init__(self, control=None):
     if alsaaudio is None:
         LOG.error("pyalsaaudio not installed")
         LOG.info("Run pip install pyalsaaudio==0.8.2")
         raise ImportError
     if control is None:
         control = alsaaudio.mixers()[0]
     self.get_mixer(control)
    def getMixers(self):
        '''
        Returns a list of all mixers available (pcm, master, etc...)

        @rtype:  list
        @return: mixers name available
        '''
        return alsaaudio.mixers()
Esempio n. 36
0
def is_muted(mixer_name=OUTPUT_MUTE):
    """Figure out if the output is muted or not."""
    if mixer_name not in alsaaudio.mixers():
        logger.error('Could not find mixer %s', mixer_name)
        return False

    mixer = alsaaudio.Mixer(mixer_name)
    return mixer.getmute()[0] == 1
Esempio n. 37
0
 def __init__(self):
     self.mixerid = ''
     for i in alsaaudio.mixers():
         if i == 'Master' or i == 'PCM' or i == 'Speaker':
             self.mixerid = i
     if self.mixerid == '':
         raise Exception('Cannot find mixer')
     self.mixer = alsaaudio.Mixer(control=self.mixerid)
Esempio n. 38
0
    def testMixer(self):
        """Open a Mixer on every card"""

        # Mixers are addressed by index, not name
        for i in range(len(alsaaudio.cards())):
            mixers = alsaaudio.mixers(i)
            for m in mixers:
                mixer = alsaaudio.Mixer(m, cardindex=i)
                mixer.close()
Esempio n. 39
0
    def testMixer(self):
        """Open a Mixer on every card"""

        # Mixers are addressed by index, not name
        for i in range(len(alsaaudio.cards())):
            mixers = alsaaudio.mixers(i)
            for m in mixers:
                mixer = alsaaudio.Mixer(m, cardindex=i)
                mixer.close()
Esempio n. 40
0
def changeVol(val):
    mixer = alsaaudio.Mixer(alsaaudio.mixers()[0])
    vol = mixer.getvolume()[0]
    if val == 1:
        vol = incrVol(mixer)
    else:
        vol = decrVol(mixer)
    mixer.setvolume(vol)
    print("volume set to", mixer.getvolume()[0])
Esempio n. 41
0
    def __init__(self, main):
        """Get names of equalizer channels if such.
        """

        self.main = main
        self.mixers = alsaaudio.mixers()
        self.equal_channels = []  # names of equalizer channels if found

        self.init_equal_channels()
Esempio n. 42
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. 43
0
 def _get_mixer_control(self):
     """Returns the first mixer control candidate that is known to ALSA"""
     candidates = self._get_mixer_control_candidates()
     for control in candidates:
         if control in alsaaudio.mixers():
             logger.info(u"Mixer control in use: %s", control)
             return control
         else:
             logger.debug(u"Mixer control not found, skipping: %s", control)
     logger.warning(u"No working mixer controls found. Tried: %s", candidates)
Esempio n. 44
0
def set_volume(card="", mixeridx=0, channel=0, value=50, direction='playback'):
    # channel = alsaaudio.MIXER_CHANNEL_ALL
    devices = alsaaudio.cards()
    try:
        idx = devices.index(card)
    except ValueError:
        idx = 0
    mixers = alsaaudio.mixers(idx)
    mixer = alsaaudio.Mixer(mixers[int(mixeridx)], cardindex=idx)
    mixer.setvolume(int(value), int(channel), direction)
    return ""
Esempio n. 45
0
def audio_env():
    """Display the cards and mixers in the audio subsystem."""
    list_of_cards = alsaaudio.cards()
    num_cards = len(list_of_cards)

    logger.debug('audio_env %s %s %s', num_cards, ' cards found: ', list_of_cards)
    logger.debug('audio_env %s %s', 'mixers =', alsaaudio.mixers() )

    for index in range(num_cards):
        logger.debug('audio_env %s %s %s %s', 'card =', list_of_cards[index], 'mixer =', alsaaudio
        .mixers(
            index))
Esempio n. 46
0
 def get_channels(self, card_index):
     try:
         self.alsa_channels[card_index] = []
         for channel in alsa.mixers(card_index):
             id = 0
             while (channel, id) in self.alsa_channels[card_index]:
                 id += 1
             mixer = alsa.Mixer(channel, id, card_index)
             if len(mixer.volumecap()):
                 self.alsa_channels[card_index].append((channel, id))
     except:
         pass
Esempio n. 47
0
def show_preferences(parent, driver, gconf_client, gconf_key):
    def refresh_devices(widget):
        new_soundcard_name = soundcard_model[widget.get_active()][0]
        new_soundcard_index = alsa_soundcards.index(new_soundcard_name)
        '''
        We temporarily block the handler for the mixer_combo 'changed' signal, since we are going
        to change the combobox contents.
        '''
        mixer_combo.handler_block(changed_handler_id)
        mixer_model.clear()
        for mixer in alsaaudio.mixers(new_soundcard_index):
            mixer_model.append([mixer])
        # Now we can unblock the handler
        mixer_combo.handler_unblock(changed_handler_id)
        # And since the list of mixers has changed, we select the first one by default
        mixer_combo.set_active(0)

    widget_tree = gtk.Builder()
    widget_tree.add_from_file(os.path.join(os.path.dirname(__file__), "volume.ui"))
    dialog = widget_tree.get_object("VolumeDialog") 
    soundcard_combo = widget_tree.get_object('SoundcardCombo')
    mixer_combo = widget_tree.get_object('MixerCombo')
    soundcard_model = widget_tree.get_object("SoundcardModel")
    mixer_model = widget_tree.get_object("MixerModel")
    alsa_soundcards = alsaaudio.cards()
    soundcard_name = g15gconf.get_string_or_default(gconf_client,
                                                    gconf_key + "/soundcard",
                                                    str(alsa_soundcards[0]))
    soundcard_index = alsa_soundcards.index(soundcard_name)
    soundcard_mixers = alsaaudio.mixers(soundcard_index)

    for card in alsa_soundcards:
        soundcard_model.append([card])
    for mixer in soundcard_mixers:
        mixer_model.append([mixer])

    g15uigconf.configure_combo_from_gconf(gconf_client, \
                                          gconf_key + "/soundcard", \
                                          "SoundcardCombo", \
                                          str(alsa_soundcards[0]), \
                                          widget_tree)

    changed_handler_id = g15uigconf.configure_combo_from_gconf(gconf_client, \
                                                               gconf_key + "/mixer", \
                                                               "MixerCombo", \
                                                                str(soundcard_mixers[0]), \
                                                                widget_tree)
    soundcard_combo.connect('changed', refresh_devices)

    dialog.set_transient_for(parent)
    dialog.run()
    dialog.hide()
Esempio n. 48
0
    def testMixerClose(self):
        "Run common Mixer methods on a closed object and verify it raises an error"

        mixers = alsaaudio.mixers()
        mixer = alsaaudio.Mixer(mixers[0])
        mixer.close()

        for m, a in MixerMethods:
            f = alsaaudio.Mixer.__dict__[m]
            if a is None:
                self.assertRaises(alsaaudio.ALSAAudioError, f, mixer)
            else:
                self.assertRaises(alsaaudio.ALSAAudioError, f, mixer, *a)
Esempio n. 49
0
def mute(direction="playback", card="", mixeridx=0, channel=0, value=0):
    devices = alsaaudio.cards()
    try:
        idx = devices.index(card)
    except ValueError:
        idx = 0
    mixers = alsaaudio.mixers(idx)
    mixer = alsaaudio.Mixer(mixers[int(mixeridx)], cardindex=idx)
    if direction == "playback":
        mixer.setmute(int(value), int(channel))
    else:
        mixer.setrec(int(value), int(channel))
    return ""
Esempio n. 50
0
    def testMixer(self):
        """Open the default Mixers and the Mixers on every card"""
        
        for d in ['default'] + list(range(len(alsaaudio.cards()))):
            if type(d) == type(0):
                kwargs = { 'cardindex': d }
            else:
                kwargs = { 'device': d }

            mixers = alsaaudio.mixers(**kwargs)
            
            for m in mixers:
                mixer = alsaaudio.Mixer(m, **kwargs)
                mixer.close()
Esempio n. 51
0
    def testMixerAll(self):
        "Run common Mixer methods on an open object"

        mixers = alsaaudio.mixers()
        mixer = alsaaudio.Mixer(mixers[0])

        for m, a in MixerMethods:
            f = alsaaudio.Mixer.__dict__[m]
            if a is None:
                f(mixer)
            else:
                f(mixer, *a)

        mixer.close()
Esempio n. 52
0
def alsa(card="ALSA"):
    devices = alsaaudio.cards()
    try:
        idx=devices.index(card)
    except ValueError:
        card = "ALSA"
        idx=devices.index(card)
    mixers = alsaaudio.mixers(idx)
    volumes = {}
    for i in range(len(mixers)):
        mixer = alsaaudio.Mixer(mixers[i], cardindex=idx)
        volumes[mixers[i]] = {'levels': mixer.getvolume(), 'mutes': mixer.getmute()}

    return render_template('alsa.html', devices=devices, volumes=volumes)
Esempio n. 53
0
 def __callback_options(self, widget):
     self.__clean()
     mixers = alsaaudio.mixers()  # List of channels
     for m in mixers:
         cb = gtk.CheckButton(m)
         active = self.__channels.count(m + "\n") > 0
         cb.set_active(active)
         # TODO make the tick boxes bigger
         self.__sldvbox.pack_start(cb, False, True, 0)
         cb.show()
     # Change which buttons are visible
     self.__buttonE.hide()
     self.__buttonO.hide()
     self.__buttonS.show()
     self.__buttonC.show()
Esempio n. 54
0
  def _find_suitable_mixers(self, card_index = -1):
    mic = None
    speaker = None

    if card_index < 0:
      for card_index in range(0, Alsa.CARD_INDICES_TO_TRY):
        try:
          mixers = alsaaudio.mixers(cardindex = card_index)

          if 'Mic' in mixers and 'Speaker' in mixers:
            mic = alsaaudio.Mixer(control = 'Mic', cardindex = card_index)
            speaker = alsaaudio.Mixer(control = 'Speaker', cardindex = card_index)
            break

        except Exception:
          pass
    else:
      mixers = alsaaudio.mixers(cardindex = card_index)

      if 'Mic' in mixers and 'Speaker' in mixers:
        mic = alsaaudio.Mixer(control = 'Mic', cardindex = card_index)
        speaker = alsaaudio.Mixer(control = 'Speaker', cardindex = card_index)

    return speaker, mic
Esempio n. 55
0
 def refresh_devices(widget):
     new_soundcard_name = soundcard_model[widget.get_active()][0]
     new_soundcard_index = alsa_soundcards.index(new_soundcard_name)
     '''
     We temporarily block the handler for the mixer_combo 'changed' signal, since we are going
     to change the combobox contents.
     '''
     mixer_combo.handler_block(changed_handler_id)
     mixer_model.clear()
     for mixer in alsaaudio.mixers(new_soundcard_index):
         mixer_model.append([mixer])
     # Now we can unblock the handler
     mixer_combo.handler_unblock(changed_handler_id)
     # And since the list of mixers has changed, we select the first one by default
     mixer_combo.set_active(0)
Esempio n. 56
0
 def get_mixers(card_index=0):
     """ Returns mixers list """
     mixers_tmp = []
     mixers_params = []
     for control in alsa.mixers(card_index):
         cid = mixers_tmp.count(control)
         mixer = MixerChannel(card_index, control, cid)
         cap = mixer.get_volumecap()
         if ( cap ):
             #if 'Playback Volume' in cap or 'Joined Volume' in cap:
             item = [control, cid]
             mixers_params.append(item)
             mixers_tmp.append(control)
         del mixer
     return mixers_params
Esempio n. 57
0
 def volume(self, relativeVolume):
     try:
         mixer = alsaaudio.Mixer(self.mixerControl, self.mixerId, self.mixerCardIdx)
         vol = mixer.getvolume()
         logging.debug('Current alsa volume: {}'.format(vol))
         vol[0] += relativeVolume
         vol[0] = max(0, min(vol[0], 100))
         mixer.setvolume(vol[0])
         return vol[0]
     except alsaaudio.ALSAAudioError:
         logging.error('No mixer found for Control: {} ID:{} Card: {}'.format(self.mixerControl, self.mixerId, self.mixerCardIdx))
         cards = alsaaudio.cards()
         logging.debug('Available cards: {}'.format(cards))
         mixers = alsaaudio.mixers(self.mixerCardIdx)
         logging.debug('Available mixer card {}: {}'.format(self.mixerCardIdx, mixers))
     return 0
Esempio n. 58
0
    def __init__(self, plugin, bar):
        UI.PopupWindow.__init__(self, bar, plugin)

        self.card_index = int(plugin.settings["card_index"])
        self.control = plugin.settings["control"]

        try:
            self.mixer = alsa.Mixer(control=self.control, cardindex=self.card_index)
        except Exception, err:
            print "Mixer plugin ERR:", err
            try:
                self.mixer = alsa.Mixer(control=alsa.mixers(self.card_index).get_mixers()[0], cardindex=self.card_index)
            except Exception, err:
                print "Mixer plugin ERR:", err
                self.mixer = None
                self.set_volume(0)
Esempio n. 59
0
 def get_mixer_list(self):
     """ Append to mixer list, mixers with equal names
     are grouped and controlled together. """
     mixerlist = []
     for mixer in alsa.mixers(self.card_index):
         try:
             if mixer not in mixerlist:
                 mixerlist.append(mixer)
                 seq = 0
             else:
                 seq += 1
             if self.control == mixer:
                 m = alsa.Mixer(control=mixer,
                         cardindex=self.card_index, id=seq)
                 self.mixerlist.append(m)
         except alsa.ALSAAudioError:
             pass
Esempio n. 60
0
def index(card=""):
    settings = Settings.query.get(1)
    if settings:
        card = settings.device
    playbacks = {}
    captures = {}
    devices = alsaaudio.cards()
    try:
        idx = devices.index(card)
    except ValueError:
        return render_template('mixers/device_error.html')
    try:
        mixers = alsaaudio.mixers(idx)
    except:
        devices = {"No ALSA Device detected"}
        return render_template('mixers/index.html', devices=devices,
                               playbacks=playbacks, captures=captures)

    for i in range(len(mixers)):
        mixer = alsaaudio.Mixer(mixers[i], cardindex=idx)

        try:
            mutes = mixer.getmute()
        except alsaaudio.ALSAAudioError:
            mutes = {}

        try:
            getrecs = mixer.getrec()
        except alsaaudio.ALSAAudioError:
            getrecs = {}

        if mixer.getvolume('playback'):
            playbacks[mixers[i]] = {'mixer': i,
                                    'levels': mixer.getvolume('playback'),
                                    'mutes': mutes}
        if mixer.getvolume('capture'):
            captures[mixers[i]] = {'mixer': i,
                                   'levels': mixer.getvolume('capture'),
                                   'mutes': getrecs}

    return render_template('mixers/index.html',
                           devices=devices,
                           playbacks=playbacks,
                           captures=captures,
                           card=card)