def set_card(self): if u'Device' in alsaaudio.cards(): _card_index = alsaaudio.cards().index(u'Device') else: _card_index = 0 if self._card_index != 0: _card_index = self._card_index os_flag = True if os.system("amixer -q -c %d sset 'Mic' %d" % (_card_index, self._volume_gain)): os_flag = False if os.system("amixer -q -c %d sset 'Auto Gain Control' %s" % (_card_index, self._volume_agc)): os_flag = False # Default attributes: Mono, 40000 Hz, 16 bit little endian samples inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, cardindex=_card_index) inp.setchannels(1) inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) inp.setrate(self._sample_rate) inp.setperiodsize(self._period_size) self._inp = inp return os_flag
def get_alsa_cards(self, cardid = None): if config.disable_alsa: return [] if cardid == None: return alsaaudio.cards() elif cardid < len(alsaaudio.cards()): return alsaaudio.cards()[cardid]
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)
def get_cardid(self, audiocard = None): if config.disable_alsa: return -1 if audiocard == None: audiocard = config.opt_dict['audio_card'] for id in range(len(alsaaudio.cards())): if alsaaudio.cards()[id] == audiocard: return id return -1
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
def main(): print('main()') #signal.signal(signal.SIGINT, signal_handler) print('str(alsaaudio.cards())' + str(alsaaudio.cards())) ear1=Ear(card=alsaaudio.cards()[0]) #'Set') # card=alsaaudio.cards()[1] ear1.start() ear2=Ear(card=alsaaudio.cards()[1]) # card=alsaaudio.cards()[1] ear2.start() t = Timer(60.0, stop) t.start() # after 30 seconds, Ear will be stopped
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 + "#")
def checksndcards(): cards = alsaaudio.cards() nrcards = len(cards) if nrcards == 0: return nrcards print "\nAvailable sound cards:\n" for i in range(0, nrcards): if len(cards[i]) < 6: print "'%s'\t\t:" % cards[i], else: print "'%s'\t:" % cards[i], dsd = checkdsd(cards[i]) if dsd == 0: print "USB device with native DSD support" elif dsd == 1: print "Not a (UAC2) USB sound card" elif dsd == 2: print "No proc entry for '%s'" % cards[i] elif dsd == 3: print "USB device, no native DSD support" else: print "Unhandled value '%d' " % dsd exit(1) print ""
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
def __init__(self): gtk.Window.__init__(self) self.cp = ConfigParser() self.cp.read(CONFIG_FILE) self.lock_mask = {} self.control_mask = {} self.card_hbox = {} self.alsa_channels = {} self.set_title("Volti Mixer") self.set_resizable(True) self.set_border_width(5) self.set_position(gtk.WIN_POS_CENTER) self.add_events(gtk.gdk.BUTTON_PRESS_MASK) self.connect('delete_event', self.quit) icon_theme = gtk.icon_theme_get_default() if icon_theme.has_icon("multimedia-volume-control"): self.set_icon_name("multimedia-volume-control") else: file = os.path.join(RES_DIR, "icons", "multimedia-volume-control.svg") self.set_icon_from_file(file) self.acards = alsa.cards() self.set_layout() self.init_controls() self.show() card_index = int(self.cp.get("global", "card_index")) self.notebook.set_current_page(card_index)
def sound_configuration(): """ Returns the (as a triplet) the card's index (zero based), raw card name and the device (playback or recording) supported by the hardware as a unicode string. @rtype: tuple @postcondition: len(return) == 3 @postcondition: isinstnace(return[0], six.integer_types) @postcondition: return[0] >= 0 @postcondition: return[1] in SoundAlsa.SOUND_CARDS_SUPPORTED @postcondition: len(return[1]) > 0 @postcondition: isinstance(return[2], six.text_type) @postcondition: len(return[2]) > 0 @raise RuntimeError: if no ALSO device could be found or if the device found cannot be configured. """ for idx, sound_card in enumerate(alsaaudio.cards()): if sound_card in SoundAlsa.SOUND_CARDS_SUPPORTED: device = f"plughw:CARD={sound_card}" if not SoundAlsa.__test_device(device, False): raise RuntimeError( "Unable to configure sound card for playback") return idx, sound_card, device raise RuntimeError( "Sound card not found by ALSA (are drivers missing?)")
def __init__(self,sampFreq,frameSize): print("auidioInput.__init__"); self.audioSampleFreq = sampFreq self.frameSize = frameSize print "Initialising Audio System" cardNo = 0 soundCards = alsaaudio.cards() for card in soundCards: print card print "Using sound card: %s" % (soundCards[cardNo]) # Set attributes: Mono, 8000 Hz, 16 bit little endian samples # PCM_NORMAL forces the system to wait for a full frame of data # when we call getFrame. self.inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NORMAL,'default') self.inp.setchannels(1) self.inp.setrate(self.audioSampleFreq) self.inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) # The period size controls the internal number of frames per period. # The significance of this parameter is documented in the ALSA api. # For our purposes, it is suficcient to know that reads from the device # will return this many frames. Each frame being 2 bytes long. # This means that the reads below will return either 320 bytes of data # or 0 bytes of data. The latter is possible because we are in nonblocking # mode. self.inp.setperiodsize(self.frameSize) print("__init__ complete")
def __init__(self, sampFreq, frameSize): print("auidioInput.__init__") self.audioSampleFreq = sampFreq self.frameSize = frameSize print "Initialising Audio System" cardNo = 0 soundCards = alsaaudio.cards() for card in soundCards: print card print "Using sound card: %s" % (soundCards[cardNo]) # Set attributes: Mono, 8000 Hz, 16 bit little endian samples # PCM_NORMAL forces the system to wait for a full frame of data # when we call getFrame. self.inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, 'default') self.inp.setchannels(1) self.inp.setrate(self.audioSampleFreq) self.inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) # The period size controls the internal number of frames per period. # The significance of this parameter is documented in the ALSA api. # For our purposes, it is suficcient to know that reads from the device # will return this many frames. Each frame being 2 bytes long. # This means that the reads below will return either 320 bytes of data # or 0 bytes of data. The latter is possible because we are in nonblocking # mode. self.inp.setperiodsize(self.frameSize) print("__init__ complete")
def test_select_output(self): cards = alsaaudio.cards() config = get_config() selected_index = 0 class FakeDropdown: """Acts like a Gtk.ComboBoxText object.""" def get_active_text(self): return cards[selected_index] self.window.on_output_card_selected(FakeDropdown()) self.assertEqual(config.get('pcm_output'), f'hw:CARD={cards[selected_index]}') with open(alsactl_asoundrc, 'r') as f: asoundrc = f.read() self.assertIn(config.get('pcm_output'), asoundrc) self.assertNotIn(cards[1], asoundrc) selected_index = 1 config.set('output_plugin', 'ab') self.window.on_output_card_selected(FakeDropdown()) self.assertEqual(config.get('pcm_output'), f'ab:CARD={cards[selected_index]}') with open(alsactl_asoundrc, 'r') as f: asoundrc = f.read() self.assertNotIn(cards[0], asoundrc) self.assertIn(config.get('pcm_output'), asoundrc)
def __init__(self): GObject.GObject.__init__(self) self.cp = ConfigParser() self.cp.read(CONFIG_FILE) self.lock_mask = {} self.control_mask = {} self.card_hbox = {} self.alsa_channels = {} self.set_title("Volti Mixer") self.set_resizable(True) self.set_border_width(5) self.set_position(Gtk.WindowPosition.CENTER) self.add_events(Gdk.EventMask.BUTTON_PRESS_MASK) self.connect('delete_event', self.quit) icon_theme = Gtk.IconTheme.get_default() if icon_theme.has_icon("multimedia-volume-control"): self.set_icon_name("multimedia-volume-control") else: file = os.path.join(RES_DIR, "icons", "multimedia-volume-control.svg") self.set_icon_from_file(file) self.acards = alsa.cards() self.set_layout() self.init_controls() self.show() card_index = int(self.cp.get("global", "card_index")) self.notebook.set_current_page(card_index)
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}." )
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))
def post(self): v_str = self.get_argument("v", default=None, strip=False) if v_str is None: self.write("-1") DEBUG(u"请输入音量值") return cards = alsaaudio.cards() INFO(cards) INFO("use card 1.") m = alsaaudio.Mixer(control='PCM', cardindex=1) try: volume = int(v_str) except ValueError: try: volume = float(v_str) self.write("-2") DEBUG(u"音量值必须为整数") return except ValueError: volume = -1 if volume == -1: self.write("-3") DEBUG(u"音量值无效:%s" % msg) return m.setvolume(volume) DEBUG(u"设置音量值为:%s" % str(volume)) self.write(RETURNCODE.SUCCESS)
def select_input_pcm(card): """Write the pcm to the configuration. Parameters ---------- card : string "Generic", "jack", ... """ # figure out if this is an actual hardware device or not if card is None: logger.debug('Unselecting the input') get_config().set('pcm_input', 'null') return cards = alsaaudio.cards() if card == 'jack': pcm_name = 'jack' elif card in cards: plugin = get_config().get('input_plugin') pcm_name = f'{plugin}:CARD={card}' else: # card unknown, the device is possibly not connected logger.warning( 'Going to write possibly invalid pcm %s to the settings', card) # might me something similar to jack, a software pcm pcm_name = card get_config().set('pcm_input', pcm_name)
def get_valid_sound_devices(): available_cards = alsaaudio.cards() if available_cards: return available_cards return ["No audio devices found."]
def get_cards(): ''' Get the names of all available audio cards @return :list<str> The names of all available audio cards ''' return alsaaudio.cards()
def main(argv): global msgID global direction global intensity global sock if len(argv) < 1: print('main.py <server ip address>') sys.exit(2) else: HOST = argv[0] # Initialize microphone here miccards = alsa.cards() micnum = len(miccards) - 1 '''mic = [alsa.PCM(alsa.PCM_CAPTURE, alsa.PCM_NORMAL)] mic.append(alsa.PCM(alsa.PCM_CAPTURE, alsa.PCM_NORMAL, miccards[1])) mic.append(alsa.PCM(alsa.PCM_CAPTURE, alsa.PCM_NORMAL, miccards[2]))''' mic = [alsa.PCM(alsa.PCM_CAPTURE,alsa.PCM_NORMAL,miccards[i]) for i in range(micnum)] for i in range(micnum): mic[i].setchannels(CHANNELS) mic[i].setrate(RATE) mic[i].setformat(FORMAT) mic[i].setperiodsize(FRAMESIZE) # Initialize SpeechRecognizer here recognizer = sr.Recognizer() # Initialize network connection here sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket (SOCK_STREAM means a TCP socket) try: sock.connect((HOST, PORT)) except socket.error, msg: print("Could not connect to server! Error: %s" % msg) sys.exit(-1)
def test_select_input(self): cards = alsaaudio.cards() config = get_config() # only show the input in the generated asoundrc to make # assertIn not get false positives. # Since there are some comments and stuff about jack in it, this # test avoids to also try to select jack. config.set('pcm_output', 'null') # first card self.window.on_input_card_selected(cards[0]) self.assertEqual(config.get('pcm_input'), f'hw:CARD={cards[0]}') with open(alsactl_asoundrc, 'r') as f: asoundrc = f.read() self.assertIn(config.get('pcm_input'), asoundrc) self.assertNotIn(cards[1], asoundrc) # selecting it a second time unselects it self.window.on_input_card_selected(cards[0]) self.assertEqual(config.get('pcm_input'), 'null') with open(alsactl_asoundrc, 'r') as f: asoundrc = f.read() self.assertNotIn(cards[0], asoundrc) self.assertNotIn(cards[1], asoundrc) # second card config.set('input_plugin', 'ab') self.window.on_input_card_selected(cards[1]) self.assertEqual(config.get('pcm_input'), f'ab:CARD={cards[1]}') with open(alsactl_asoundrc, 'r') as f: asoundrc = f.read() self.assertNotIn(cards[0], asoundrc) self.assertIn(config.get('pcm_input'), asoundrc)
def checksndcards(): cards = alsaaudio.cards() nrcards = len(cards) if nrcards == 0: return nrcards print "\nAvailable sound cards:\n" for i in range(0, nrcards): if len(cards[i]) < 6: print "'%s'\t\t:" % cards[i], else: print "'%s'\t:" % cards[i], dsd = checkdsd(cards[i]) if dsd == 0: print "USB device with native DSD support" elif dsd == 1: print "Not a (UAC2) USB sound card" elif dsd == 2: print "No proc entry for '%s'" % cards[i] elif dsd == 3: print "USB device, no native DSD support" else: print "Unhandled value '%d' " % dsd exit (1) print ""
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)
def __init__(self, rate=44100, period=1024, channels=2, aformat=alsaaudio.PCM_FORMAT_S16_LE, cardindex=-1, *args, **kwargs): Sampler.__init__(self, rate=rate, period=period, *args, **kwargs) self._channels = channels self._format = aformat self._cardindex = cardindex # Find out which card to use from user cards = alsaaudio.cards() for i, c in enumerate(cards): print("{}: {}".format(i, c)) card = int(input("Please choose a card from the above: ")) self._cardindex = card # Instantiate our alsaaudio PCM self._inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, cardindex=self._cardindex) # Set some values on our new capture PCM self._inp.setchannels(self._channels) self._inp.setrate(self._rate) self._inp.setformat(self._format) self._inp.setperiodsize(self._period)
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
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)
def __init__(self): UpdateThread.__init__(self, "AUDIO-Thread") self.setSleepDuration(1) self._soundsDir = os.path.dirname(__file__) + "/sounds/" self._speakerCardIdx = 0 # TODO self._hjackCardIdx = audio.cards().index('Headphones') gpio.setmode(gpio.BCM) gpio.setup(4, gpio.IN)
def get_cards(): """List all cards, including options such as jack.""" cards = alsaaudio.cards() if services.is_jack_running(): cards.append('jack') if len(cards) == 0: logger.error('Could not find any card') return cards
def assert_loopback_device(): """ Raise an error if there is no loopback device initialized """ card_list = alsaaudio.cards() if "Loopback" not in card_list: raise ValueError("There is no Loopback module loaded by ALSA. Loopback is needed by the program. " + "Try loading it via modprobe or add it to /etc/modules or to a file in /etc/modules.d/.")
def show_cards(card=None): available_cards = alsaaudio.cards() print 'Available sound cards:' print ' [%s]' % ', '.join(available_cards) print '' if card: if card not in available_cards: available_cards = [] return available_cards
def listAlsaaudioPlaybackCards(self): playbackCardList = [] for card in alsaaudio.cards(): try: alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL, card=card) playbackCardList.append(card) except: pass return playbackCardList
def test_detect_jack(self): # cards return only the actual hardware cards, self.assertEqual(alsaaudio.cards(), ['FakeCard1', 'FakeCard2']) # but since is_jack_running is patched to return true, it is added # to the lists. self.assertEqual(get_cards(), ['FakeCard1', 'FakeCard2', 'jack']) self.assertEqual( [input_row.card for input_row in self.window.input_rows], ['FakeCard1', 'FakeCard2', 'jack'])
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()
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]
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 ""
def __init__(self, cardindex = 0, mixername = 'Master'): ''' Constructor @param cardindex:int The index of the audio card @param mixername:str The name of the mixer ''' self.cardindex = cardindex self.cardname = alsaaudio.cards()[cardindex] self.mixername = mixername self.mixer = alsaaudio.Mixer(self.mixername, 0, self.cardindex)
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))
def get_cards(self): """ Returns cards list """ cards = [] acards = alsa.cards() for index, card in enumerate(acards): try: self.get_mixers(index)[0] except IndexError: cards.append(None) else: cards.append(acards[index]) return cards
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()
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()
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])
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 ""
def list_sound_cards(): if platform.uname()[0]=='Linux': return aa.cards() else: p = pyaudio.PyAudio() info = p.get_host_api_info_by_index(0) numdevices = info.get('deviceCount') devicenamelist = [] for i in range(0, numdevices): if p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels') > 0: devicename = "DevID "+str(i) devicenamelist.append(devicename) return devicenamelist
def get_cards(): """ Returns cards list """ cards = [] acards = alsa.cards() log.Notice("getting card list", 1) for index, card in enumerate(acards): try: assert len (CardInfo.get_mixers(index)) > 0 except IndexError, err: log.Warn("Card error: %s" % str(err)) cards.append(None) else: cards.append(card)
def get_devices(driver): """Return a list if valid devices for the given driver""" if driver not in available_drivers: raise MixerError("Invalid driver: '{0}'".format(str(driver))) if driver == 'ALSA': devs = alsaaudio.cards() elif driver == 'OSS': # If AUDIODEV is not set, we filter it from the list devs= [x for x in [os.getenv('AUDIODEV'), "/dev/mixer"] if x is not None] if len(devs) < 1: raise MixerError("Could not find any devices for {0}".format(driver)) else: return devs
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)
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()
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()
def main(argv): if len(argv) < 1: print('main.py <server ip address>') sys.exit(2) else: HOST = argv[0] # Initialize microphone here miccards = alsa.cards() micnum = len(miccards) - 1 mic = [alsa.PCM(alsa.PCM_CAPTURE, alsa.PCM_NORMAL)] mic.append(alsa.PCM(alsa.PCM_CAPTURE, alsa.PCM_NORMAL, miccards[1])) mic.append(alsa.PCM(alsa.PCM_CAPTURE, alsa.PCM_NORMAL, miccards[2])) #mic = [alsa.PCM(alsa.PCM_CAPTURE, alsa.PCM_NORMAL, miccards[i]) for i in range(micnum)] for i in range(micnum): mic[i].setchannels(CHANNELS) mic[i].setrate(RATE) mic[i].setformat(FORMAT) mic[i].setperiodsize(FRAMESIZE) # Initialize SoundHound here # Listener for the mic input class MyListener(houndify.HoundListener): def onPartialTranscript(self, transcript): pass #if transcript != "": print "Partial transcript: " + transcript def onFinalResponse(self, response): responseStr = str(response) splitString = responseStr.split("'") for i in range(len(splitString)): if splitString[i] == 'Transcription': print "Final response:" + splitString[i+2] # print "Final response: " + str(response) def onTranslatedResponse(self, response): print "Translated response: " + response def onError(self, err): print "ERROR" client = houndify.StreamingHoundClient(CLIENT_KEY, CLIENT_ID) ## Pretend we're at SoundHound HQ. Set other fields as appropriate client.setLocation(37.388309, -121.973968) # Initialize network connection here sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket (SOCK_STREAM means a TCP socket) try: sock.connect((HOST, PORT)) except socket.error, msg: print("Could not connect to server! Error: %s" % msg) sys.exit(-1)
def __init__(self): self.card = None try: for card in alsaaudio.cards(): if card.startswith("U0x") or card.startswith("Device") or card.startswith("PCH"): self.card = 'sysdefault:CARD=%s' % card break except: pass if not self.card: Tracer()() sys.exit('Unable to find requested sound card.') self.configure_device() self.init_settings()