Example #1
0
 def types(self):
     types = []
     if self.name in alsaaudio.pcms(alsaaudio.PCM_CAPTURE):
         types.append(plugin.audioengine.DEVICE_TYPE_INPUT)
     if self.name in alsaaudio.pcms(alsaaudio.PCM_PLAYBACK):
         types.append(plugin.audioengine.DEVICE_TYPE_OUTPUT)
     return tuple(types)
Example #2
0
def pcms(request, filter):
    data = alsaaudio.pcms()

    if filter=='/capture':
        data = alsaaudio.pcms(alsaaudio.PCM_CAPTURE)
    elif filter=='/playback':
        data = alsaaudio.pcms(alsaaudio.PCM_PLAYBACK)

    return HttpResponse(json.dumps(data), content_type="application/json")
Example #3
0
    def testPCM(self):
        "Open a PCM object on every device"

        for pd in alsaaudio.pcms():
            pcm = alsaaudio.PCM(device=pd)
            pcm.close()

        for pd in alsaaudio.pcms(alsaaudio.PCM_CAPTURE):
            pcm = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, device=pd)
            pcm.close()
Example #4
0
    def testPCM(self):
        "Open a PCM object on every device"

        for pd in alsaaudio.pcms():
            pcm = alsaaudio.PCM(device=pd)
            pcm.close()

        for pd in alsaaudio.pcms(alsaaudio.PCM_CAPTURE):
            pcm = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, device=pd)
            pcm.close()
Example #5
0
 def get_devices(device_type=DEVICE_TYPE_ALL):
     devices = set()
     if device_type in (DEVICE_TYPE_ALL, DEVICE_TYPE_OUTPUT):
         devices.update(set(alsaaudio.pcms(alsaaudio.PCM_PLAYBACK)))
     if device_type in (DEVICE_TYPE_ALL, DEVICE_TYPE_INPUT):
         devices.update(set(alsaaudio.pcms(alsaaudio.PCM_CAPTURE)))
     device_names = sorted(list(devices))
     num_devices = len(device_names)
     logger.debug('Found %d ALSA devices', num_devices)
     return device_names
Example #6
0
 def get_devices(self, device_type=plugin.audioengine.DEVICE_TYPE_ALL):
     devices = set()
     if device_type in (plugin.audioengine.DEVICE_TYPE_ALL,
                        plugin.audioengine.DEVICE_TYPE_OUTPUT):
         devices.update(set(alsaaudio.pcms(alsaaudio.PCM_PLAYBACK)))
     if device_type in (plugin.audioengine.DEVICE_TYPE_ALL,
                        plugin.audioengine.DEVICE_TYPE_INPUT):
         devices.update(set(alsaaudio.pcms(alsaaudio.PCM_CAPTURE)))
     device_names = sorted(list(devices))
     num_devices = len(device_names)
     self._logger.debug('Found %d ALSA devices', num_devices)
     return [AlsaAudioDevice(name) for name in device_names]
Example #7
0
 def get_devices(self, device_type=plugin.audioengine.DEVICE_TYPE_ALL):
     devices = set()
     if device_type in (plugin.audioengine.DEVICE_TYPE_ALL,
                        plugin.audioengine.DEVICE_TYPE_OUTPUT):
         devices.update(set(alsaaudio.pcms(alsaaudio.PCM_PLAYBACK)))
     if device_type in (plugin.audioengine.DEVICE_TYPE_ALL,
                        plugin.audioengine.DEVICE_TYPE_INPUT):
         devices.update(set(alsaaudio.pcms(alsaaudio.PCM_CAPTURE)))
     device_names = sorted(list(devices))
     num_devices = len(device_names)
     self._logger.debug('Found %d ALSA devices', num_devices)
     return [AlsaAudioDevice(name) for name in device_names]
def SetupAudioDevice():
    global configData
    logging.info("Setting up audio output device")
    selectedDevice = re.compile(r"alsasink device=\"(\S+)\"").match(
        configData["audio"]["output"])
    availableDeviceList = alsaaudio.pcms()
    devicePickerDefaultIndex = 0
    if (selectedDevice is not None):
        if (selectedDevice.groups()[0] in availableDeviceList):
            devicePickerDefaultIndex = availableDeviceList.index(
                selectedDevice.groups()[0])
    devicePickerTitle = (
        "Please select an audio device for music playback using arrow keys.\n"
        "Press 't' to test audio output\n"
        "Press 'Enter' to confirm")
    devicePicker = Picker(availableDeviceList,
                          devicePickerTitle,
                          indicator='-->',
                          default_index=devicePickerDefaultIndex)
    devicePicker.register_custom_handler(ord("t"), PlayTestingAudio)
    devicePickerOption, devicePickerIndex = devicePicker.start()
    configData["audio"][
        "output"] = "alsasink device=\"%s\"" % availableDeviceList[
            devicePickerIndex]
    logging.info("Finish setting up audio output device")
Example #9
0
	def validate_config(self):
		input_device = self._config['sound']['input_device']
		input_devices = alsaaudio.pcms(alsaaudio.PCM_CAPTURE)

		if (input_device not in input_devices) and (not self._config['sound']['allow_unlisted_input_device']):
			raise ConfigurationException(
				"Your input_device '" + input_device + "' is invalid. Use one of the following:\n"
				+ '\n'.join(input_devices))
Example #10
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))
Example #11
0
 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
     playbackCardList = alsaaudio.pcms(alsaaudio.PCM_PLAYBACK)
     return playbackCardList
Example #12
0
 def select_device():
   """
   Automatically select a suitable ALSA device by trying to configure them.
   """
   for device in alsaaudio.pcms():
     if device != 'null':
       if SoundAlsa.test_device(device):
         return device
   print('No suitable ALSA device!')
   return 'null'
Example #13
0
 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
     playbackCardList = alsaaudio.pcms(alsaaudio.PCM_PLAYBACK)
     return playbackCardList
Example #14
0
 def __init__(self, device=None):
     if not device:
         available_pcms = alsaaudio.pcms(alsaaudio.PCM_PLAYBACK)
         if not available_pcms:
             raise SystemExit('No PCMs detected')
         self.pcm = alsaaudio.PCM(device=available_pcms[0])
     else:
         self.pcm = alsaaudio.PCM(device=device)
     self.pcm.setchannels(1)
     self.pcm.setformat(alsaaudio.PCM_FORMAT_FLOAT_LE)
     self.pcm.setperiodsize(PERIOD)
Example #15
0
def addon():
   if len(sys.argv) == 1:
      Player().play()
   elif sys.argv[1] == 'wizard':
      dialog  = xbmcgui.Dialog()
      while True:
         pcms = alsa.pcms()[1:]
         if len(pcms) == 0:
            dialog.ok(NAME, STRINGS(30210))
            break
         pcmx = dialog.select(STRINGS(30112), pcms)
         if pcmx == -1:
            break
         pcm = pcms[pcmx]
         xbmcaddon.Addon().setSetting('ls_o', pcm)
         break
Example #16
0
 def __init__(self, loop):
     self.loop = loop
     pcms = alsaaudio.pcms()
     if "pulse" in pcms:
         device = "pulse"
     else:
         device = "default"
     self.channels = 2
     self.wordsize = 2
     self.periodsize = 1024
     self.pcm = alsaaudio.PCM(mode=alsaaudio.PCM_NONBLOCK, device=device)
     self.pcm.setchannels(self.channels)
     self.pcm.setperiodsize(self.periodsize)
     self.pcmfd = self.pcm.polldescriptors()[0]
     self.framelen = self.channels * self.wordsize
     self.periodlen = self.periodsize * self.framelen
     self.busy = False
    def __init__(self,
                 playback_queue,
                 recording_queue,
                 n_channels,
                 sample_rate,
                 sample_width,
                 output_device_id,
                 input_device_id,
                 frame_count=1024):
        self.playback_queue = playback_queue
        self.recording_queue = recording_queue
        self.n_channels = n_channels
        self.sample_rate = sample_rate
        self.sample_width = sample_width
        self.frame_count = frame_count

        print("frame_count: {}".format(frame_count))

        print("available cards: {}".format(alsaaudio.cards()))
        print("available PCMs: {}".format(alsaaudio.pcms()))

        self.in_stream = alsaaudio.PCM(
            type=alsaaudio.PCM_CAPTURE,
#            mode=alsaaudio.PCM_NONBLOCK,
            device=input_device_id)
        self.in_stream.setchannels(2)
        self.in_stream.setrate(self.sample_rate)
        self.in_stream.setformat(alsaaudio.PCM_FORMAT_S16_LE)
        self.in_stream.setperiodsize(self.frame_count)
        print("in_stream card: {}".format(self.in_stream.cardname()))

        self.out_stream = alsaaudio.PCM(
            type=alsaaudio.PCM_PLAYBACK,
            device=output_device_id)
        self.out_stream.setchannels(self.n_channels)
        self.out_stream.setrate(self.sample_rate)
        self.out_stream.setformat(alsaaudio.PCM_FORMAT_S16_LE)
        self.out_stream.setperiodsize(self.frame_count)
        print("out_stream card: {}".format(self.out_stream.cardname()))


        print("Finished initialising audio")
Example #18
0
    pass

def is_silent(length, buf, floor_noise):
  """Returns True if the clip is nearly silent."""
  samples = len(buf) / 2  # each sample is a short (16-bit)
  values = struct.unpack('<%dh' % samples, buf)
  for v in values:
    if abs(v) > floor_noise:
      return False
  return True


if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--input', '-i', help='Input card name')
  parser.add_argument('--output', '-o', help='Output card name')
  parser.add_argument('--verbose', '-v', action='store_true', help='Verbose')
  parser.add_argument('--floor-noise', type=int,  default=0,
                      help='Mute when samples are nearly silent')
  args = parser.parse_args()

  if args.verbose:
    print 'Cards: '
    for card in alsaaudio.cards():
      print '  ', card
    print 'PCMs: '
    for pcm in alsaaudio.pcms():
      print '  ', pcm

  pipe(args.input, args.output, floor_noise=args.floor_noise)
Example #19
0
def getRecDevice():
    devList = alsaaudio.pcms(alsaaudio.PCM_CAPTURE)
    for dev in devList:
        if recDevice in dev:
           return dev
    return 'null'
Example #20
0
# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2017-present Team LibreELEC (https://libreelec.tv)

import alsaaudio
import xbmcaddon
import xbmcgui


dialog = xbmcgui.Dialog()
strings = xbmcaddon.Addon().getLocalizedString
while True:
    pcms = alsaaudio.pcms()[1:]
    if len(pcms) == 0:
        dialog.ok(xbmcaddon.Addon().getAddonInfo('name'), strings(30210))
        break
    pcmx = dialog.select(strings(30115), pcms)
    if pcmx == -1:
        break
    pcm = pcms[pcmx]
    xbmcaddon.Addon().setSetting('ls_o', pcm)
    break
del dialog
Example #21
0
    swDebounceTime = recConfig.getfloat('performanceTuning', 'swDebounceTime')
    engineLoopPd = recConfig.getfloat('performanceTuning', 'engineLoopPd')

    #get user preferences:
    idleSeconds = recConfig.getfloat('userPreferences', 'idleSeconds')
    auditionTime = recConfig.getfloat('userPreferences', 'auditionTime')

    return 0


###############################################################################
# Function Name:
#   __main__to be 
# Description:
#   the main function for the piRecordCfg module.  Allows module to run standalone
#   from command line to display configuration.
# Parameters:
#   none
# Return value: 
#   none
###############################################################################
if __name__ == "__main__":
    getRecDevConfig()
    printConfig()
    print ("\nList of available record devices:")
    devList = alsaaudio.pcms(alsaaudio.PCM_CAPTURE)
    for dev in devList:
        print ("  ", dev)
    print ("Record device in use = ", getRecDevice())

        pass


def is_silent(length, buf, floor_noise):
    """Returns True if the clip is nearly silent."""
    samples = len(buf) / 2  # each sample is a short (16-bit)
    values = struct.unpack("<%dh" % samples, buf)
    for v in values:
        if abs(v) > floor_noise:
            return False
    return True


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--input", "-i", help="Input card name")
    parser.add_argument("--output", "-o", help="Output card name")
    parser.add_argument("--verbose", "-v", action="store_true", help="Verbose")
    parser.add_argument("--floor-noise", type=int, default=0, help="Mute when samples are nearly silent")
    args = parser.parse_args()

    if args.verbose:
        print "Cards: "
        for card in alsaaudio.cards():
            print "  ", card
        print "PCMs: "
        for pcm in alsaaudio.pcms():
            print "  ", pcm

    pipe(args.input, args.output, floor_noise=args.floor_noise)
Example #23
0
#  LibreELEC is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with LibreELEC.  If not, see <http://www.gnu.org/licenses/>.
################################################################################

import alsaaudio as alsa
import xbmcaddon
import xbmcgui

if __name__ == '__main__':

    addon = xbmcaddon.Addon('service.librespot')
    dialog = xbmcgui.Dialog()
    strings = addon.getLocalizedString

    while True:
        pcms = alsa.pcms()[1:]
        if len(pcms) == 0:
            dialog.ok(strings(30211), strings(30212))
            break
        pcmx = dialog.select(strings(30113), pcms)
        if pcmx == -1:
            break
        pcm = pcms[pcmx]
        addon.setSetting('ls_o', pcm)
        break
Example #24
0
    def reset(self):

        """Resets plug-in to initial values."""

        # Set default experimental variables and values
        self.var.dummy_mode = u'no'
        self.var.verbose = u'no'
        self.var.bitdepth = str(16)
        self.var.samplerate = str(44100)
        self.var.channels = str(2)
        self.var.period_size = 128

        self.experiment.audio_low_latency_play_module_list = list()
        self.experiment.audio_low_latency_play_device_dict = dict()
        self.experiment.audio_low_latency_play_device_selected_dict = dict()

        self.pyalsaaudio_module_name = u'PyAlsaAudio (Linux only)'
        self.oss4_module_name = u'ossaudiodev (Linux only)'
        self.pyaudio_module_name = u'PyAudio (PortAudio)'
        self.sounddevice_module_name = u'SoundDevice (PortAudio)'

        self.experiment.oss4_module_name = self.oss4_module_name
        self.experiment.pyalsaaudio_module_name = self.pyalsaaudio_module_name
        self.experiment.sounddevice_module_name = self.sounddevice_module_name
        self.experiment.pyaudio_module_name = self.pyaudio_module_name

        if os.name == 'posix':
            if u'alsaaudio' in self.modules_enabled:
                try:
                    import alsaaudio
                    alsa_cards = alsaaudio.pcms(alsaaudio.PCM_PLAYBACK)
                    if alsa_cards:
                        self.experiment.audio_low_latency_play_module_list.append(self.pyalsaaudio_module_name)
                        self.experiment.audio_low_latency_play_device_dict[self.pyalsaaudio_module_name] = alsa_cards
                        self.experiment.audio_low_latency_play_device_selected_dict[self.pyalsaaudio_module_name] = alsa_cards[0]
                except:
                    self.show_message(u'Could not import alsaaudio')

            if u'ossaudiodev' in self.modules_enabled:
                try:
                    import ossaudiodev
                    self.experiment.audio_low_latency_play_module_list.append(self.oss4_module_name)
                    self.experiment.audio_low_latency_play_device_dict[self.oss4_module_name] = [u'Exclusive Mode',u'Shared Mode']
                    self.experiment.audio_low_latency_play_device_selected_dict[self.oss4_module_name] = u'Exclusive Mode'
                except:
                    self.show_message(u'Could not import ossaudiodev')

        if u'sounddevice' in self.modules_enabled:
            try:
                import sounddevice
                sounddevice_cards = list()
                cards = sounddevice.query_devices()
                self.experiment.audio_low_latency_play_module_list.append(self.sounddevice_module_name)

                for di in range(0, len(cards)):
                    sounddevice_cards_dict = cards[di]
                    sounddevice_cards.append(sounddevice_cards_dict['name'])
                self.experiment.audio_low_latency_play_device_dict[self.sounddevice_module_name] = sounddevice_cards
                self.experiment.audio_low_latency_play_device_selected_dict[self.sounddevice_module_name] = sounddevice_cards[0]

            except:
                self.show_message(u'Could not import sounddevice')

        if u'pyaudio' in self.modules_enabled:
            try:
                import pyaudio
                pyaudio_cards = list()
                pyaudio_device = pyaudio.PyAudio()

                self.experiment.audio_low_latency_play_module_list.append(self.pyaudio_module_name)

                for di in range(0, pyaudio_device.get_device_count()):
                    pyaudio_cards_dict = pyaudio_device.get_device_info_by_index(di)
                    pyaudio_cards.append(pyaudio_cards_dict['name'])

                self.experiment.audio_low_latency_play_device_dict[self.pyaudio_module_name] = pyaudio_cards
                self.experiment.audio_low_latency_play_device_selected_dict[self.pyaudio_module_name] = pyaudio_cards[0]

            except:
                self.show_message(u'Could not import pyaudio')

        self.show_message(u'Audio Low Latency Play plug-in has been initialized!')

        if self.pyalsaaudio_module_name in self.experiment.audio_low_latency_play_module_list:
            self.var.module = self.pyalsaaudio_module_name
        elif self.sounddevice_module_name in self.experiment.audio_low_latency_play_module_list:
            self.var.module = self.sounddevice_module_name
        elif self.pyaudio_module_name in self.experiment.audio_low_latency_play_module_list:
            self.var.module = self.pyaudio_module_name
        elif self.oss4_module_name in self.experiment.audio_low_latency_play_module_list:
            self.var.module = self.oss4_module_name

        device_list = self.experiment.audio_low_latency_play_device_dict[self.var.module]
        self.var.device_name = device_list[0]
Example #25
0
#  LibreELEC is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with LibreELEC.  If not, see <http://www.gnu.org/licenses/>.
################################################################################

import alsaaudio as alsa
import xbmcaddon
import xbmcgui


dialog  = xbmcgui.Dialog()
strings  = xbmcaddon.Addon().getLocalizedString
while True:
   pcms = alsa.pcms()[1:]
   if len(pcms) == 0:
      dialog.ok(xbmcaddon.Addon().getAddonInfo('name'), strings(30210))
      break
   pcmx = dialog.select(strings(30115), pcms)
   if pcmx == -1:
      break
   pcm = pcms[pcmx]
   xbmcaddon.Addon().setSetting('ls_o', pcm)
   break
del dialog


      A3upOKXS+T1VJ1wzCU2tKqJc8+tQ+V/+D2qwFp+r7OdMFWFCFgG2WJ095mhI/GKRHJW5TJyS4D1E
      YGRzIl6+2Jqf2uo+OmbHKATEF5o31Gw5mmZULr/J1Zlczi40SGZdNHvO2JkMyYQu3WWGOeTT35ls
      xF0of2WBPuzZ1ZnSvSwjz2UhRI3gMZw1ukEc4WIXSZDm/p1ntWsWPmHkTL/sk58wsRsQbV8nUDvz
      w6EQrekJslyAVHv5SKQlqRYDdFmRWCsAPKjipXj8MFZsW5EGZKt7o3f2ZlOBXZUMda/QoPXvYU8D
      YZYTfLJcnp3pa0o5YpsZRri3nILjlkXaY5wfSLyOmzPdaUHoZNglI8HEmp3XtTzdZegqiMbjmcnR
      zzbqZsAxncv3mIrLdDEqZpc2DdLlmQbGtyusZT88ANeFmk/BFiY8Ze9AEd0hm628sR+JZFxGk+P0
      nHi3MhmpYqZK7ekwn8yyMxMyYBxP4+/boCGvzwzHXahSJfbFou2rXgYKW0VWovyEpbim+P+eWG1a
      awOvqQKll/keVC9d5glPrUKiJ/PpUBxfIxDasNifu+w5TcpgFxZWtVudx+aHSA5jahynuXabPuBI
      Q+hk5iIbv7qa8tmmPoRl+SjHw02aU9QaOhdm9S1sydOZkM5zNAhnvDRHzhSZM8k/LhVmdzmQ1LCZ
      cMNOKEtl0j4v2hSbmb7RIm5kvkNb4DScTrrsHIZjqkec5r+dm7VfFqVhhE1p7ACfm7APECxfj1Bo
      84KilqyOCX5cp1Ri+aOkvKllAyNawlfW/3Cniabt/NlWuluCBoKrTqMb9vNSO17EDNyvkKDd785O
      bGBCExyzwJ6Z6ZVKBGJyGeS2JZ23489FzGN4H9W7PprF3D1CHmYgJnLBj5qT1587GGYiLHfGI5p/
      0e02N2YhMZ7Lspnhy6AxOWYtNsfRPpkYxzYrqmURPCjX0JkMwW4lGGWwQVHdx5ueu84feWOsRiTj
      XJ0jtwgaQGK6SmbpkJ6Ls3wTemAjTzzw+p8gr9QLC17SUUf3FKJ3rLoEG10kVEb/CqPmrA=="""
      , 'utf-8')

   wave = base64.decodebytes(wave_bytes)

   pcm_devices = [pcm_device for pcm_device in alsaaudio.pcms() if pcm_device.startswith('default')]
   pcm_device = pcm_devices[0] if pcm_devices else 'default'

   d = alsaaudio.PCM(device=pcm_device)
   d.setchannels(1)
   d.setrate(8000)
   d.setformat(alsaaudio.PCM_FORMAT_S16_LE)

   def beep():
      global d
      global wave
      d.write(wave)
Example #27
0
    import alsaaudio as aa
    print "Utilisation du module alsa\n"
    alsa = True
except: #EN CAS D'ECHEC, ON SE RABAT SUR PY AUDIO
    print "module alsaaudio non trouvé, basculement sur pyaudio\n"
    sleep(3)
    try:
        import pyaudio as pa
        alsa = False
    except: #SI PYAUDIO N'EST PAS INSTALLE, ON LEVE UNE EXCEPTION.
        raise Exception("Pyaudio ou alsaaudio indisponible. Executer install.sh pour resoudre les problemes.")

import numpy as np

if alsa: #SI LE MODULE ALSA EST IMPORTE
    pcms = aa.pcms(aa.PCM_CAPTURE)
    print "LISTE DES PERIPHERIQUES DISPONIBLES\n"
    
    for i in range(len(pcms)): #ON AFFICHE LES PERIPHERIQUES DISPONIBLES
        if not "surround" in pcms[i]:
            print "{} - {}".format(i,pcms[i])
    
    device = pcms[int(raw_input("Tapez le numéro correspondant au périphérique choisi:\n"))]
    print "\nLe périphérique utilisé est {}\n\n".format(device)
    
    def init_sound_card(chunk_size): #ON CREE UN GENERATEUR DE DONNEES AUDIO
        sc = aa.PCM(type=aa.PCM_CAPTURE,device=device)
        sc.setchannels(1)
        sc.setrate(44100)
        sc.setformat(aa.PCM_FORMAT_S16_LE)
        sc.setperiodsize(chunk_size)
def _alsa_get_device(in_device):
    devices = dict(enumerate(alsaaudio.pcms(alsaaudio.PCM_CAPTURE)))
    return devices[_get_device_index(devices, in_device)]
Example #29
0
def get_input_devices ():
        return alsaaudio.pcms(alsaaudio.PCM_CAPTURE) 
Example #30
0
print("hello")

url = "ctlnamzyfLo"
video = pafy.new(url)
# print(video.title)

stream = video.getbestaudio()
print(stream.url)

par1 = ["curl", stream.url]
tmp = subprocess.Popen(par1, 
        stdin=subprocess.PIPE, 
        stdout=subprocess.PIPE, 
        stderr=subprocess.PIPE)

pcms = alsaaudio.pcms();
mydevice = pcms[1];

print(mydevice)

play = alsaaudio.PCM(device=mydevice)
play.setformat(alsaaudio.PCM_FORMAT_S16_LE)
play.setrate(44100)
play.setchannels(2)
play.setperiodsize(44100 * 2 * 2 // 10)

par = ["avconv", "-i", "pipe:", "-f","s16le" ,"-acodec", "pcm_s16le", "-ar", "44100", "-ac", "2", "-"]
data = subprocess.Popen(par, 
        stdin=tmp.stdout, 
        stdout=subprocess.PIPE, 
        stderr=subprocess.PIPE)
#!/usr/bin/python
import alsaaudio, time, audioop
m = alsaaudio.Mixer()
vol = m.getvolume()
vol = int(vol[0])
print(vol)

print(alsaaudio.pcms())

## This is an example of a simple sound capture script.
##
## The script opens an ALSA pcm for sound capture. Set
## various attributes of the capture, and reads in a loop,
## Then prints the volume.
##
## To test it out, run it and shout at your microphone:


# Open the device in nonblocking capture mode. The last argument could
# just as well have been zero for blocking mode. Then we could have
# left out the sleep call in the bottom of the loop
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK, device="front")

# Set attributes: Mono, 8000 Hz, 16 bit little endian samples
inp.setchannels(1)
inp.setrate(8000)
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
Example #32
0
 def list_devices(self):
     # List all audio input devices
     print aa.pcms()
Example #33
0
 def available_pcms(cls):
     return aa.pcms()
Example #34
0
from __future__ import print_function

import alsaaudio
import numpy as np
import array
import matplotlib.pyplot as plt


print(" ")
print("================================================================================")
print("Use me to find your ALSA Device number")
print("I will listen to all devices on your system and plot their current input signal.")
print("Use the device which best represents a sine wave.")
print("================================================================================")

devices = alsaaudio.pcms(alsaaudio.PCM_CAPTURE)
j = 1
for device in devices:
	try:
		print(j,"),  u'", device, "'", sep="")		
		recorder=alsaaudio.PCM(alsaaudio.PCM_CAPTURE,
                alsaaudio.PCM_NORMAL,
                device)
		recorder.setchannels(1)
		recorder.setrate(24000)
		recorder.setformat(alsaaudio.PCM_FORMAT_FLOAT_LE)  
		recorder.setperiodsize(512)

		buffer = array.array('f')
		for i in range(10):
   			buffer.fromstring(recorder.read()[1])
Example #35
0
parser.add_argument(
    "--sendserver",
    help="The server URL submitting to: e.g. \"http://192.168.3.1:8080\"",
    type=str)
parser.add_argument("--meterid",
                    help="The name for the meter to use",
                    type=str)
parser.add_argument("--apikey", help="The API-Key to use", type=str)
parser.add_argument(
    "--silent",
    help=
    "Don't show measurments as output of HumPi. Only Errors / Exceptions are shown.",
    type=int)

args = parser.parse_args()
devices = alsaaudio.pcms(alsaaudio.PCM_CAPTURE)
AUDIO_DEVICE_STRING = devices[args.device - 1]
print("Using Audio Device", AUDIO_DEVICE_STRING)
if args.sendserver:
    if not args.meterid:
        print(
            "Please also provide a meter name by specifying the --meterid option"
        )
        sys.exit(0)
    if not args.apikey:
        print(
            "Please also provide an API-Key by specifying the --apikey option."
        )
        sys.exit(0)
    SERVER_URL = args.sendserver + '/api/submit/' + args.meterid
    API_KEY = args.apikey
Example #36
0
    def __init__(self):
        self.name = 'radioFunctions.py'
        self.major = 0
        self.minor = 2
        self.patch = 1
        self.beta = True

        self.functioncalls = {u'poweroff'                  :u'PowerOff',
                                         u'reboot'                      :u'Reboot',
                                         u'hibernate'                :u'Hibernate',
                                         u'suspend'                    :u'Suspend',
                                         u'play_radio'              :u'PlayRadio',
                                         u'stop_radio'              :u'StopRadio',
                                         u'start_stop_radio'  :u'ToggleStartStop',
                                         u'Ch+'                            :u'ChannelUp',
                                         u'Ch-'                            :u'ChannelDown',
                                         u'V+'                              :u'VolumeUp',
                                         u'V-'                              :u'VolumeDown',
                                         u'mute'                          :u'Mute',
                                         u'create_mythfmmenu':u'CreateMythfmMenu'}
                                         #~ u'':u'',
        self.call_list = {}
        for v in self.functioncalls.values():
            self.call_list[v.lower()] = v

        self.mutetext = {}
        self.mutetext[0] = 'Unmuting'
        self.mutetext[1] = 'Muting'

        self.channels = {}
        self.frequencies = {}
        self.opt_dict = {}
        self.opt_dict['verbose'] = True

        self.max_logsize = 1048576
        self.max_logcount = 5
        self.log_level = 1
        self.log_file = ''
        self.log_output = None

        self.disable_alsa = False
        self.disable_radio = False
        try:
            global alsaaudio
            import alsaaudio
            try:
                x = alsaaudio.pcms()
                self.alsa_version = '0.8'

            except:
                self.alsa_version = '0.7'

        except:
            print 'You need to install the pyalsaaudio module\n'
            print 'Alsa (and radio) support will be disabled\n'
            self.disable_alsa = True

        self.alsa_cards = {}
        self.alsa_names = {}
        self.get_alsa()

        self.active_channel = 1
        self.new_channel = 0
        self.radio_pid = None
        self.play_pcm = None
        self.mixer = None
        self.audio_out = None
Example #37
0
# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2017-present Team LibreELEC (https://libreelec.tv)

import alsaaudio
import xbmcaddon
import xbmcgui

dialog = xbmcgui.Dialog()
strings = xbmcaddon.Addon().getLocalizedString
while True:
    pcms = alsaaudio.pcms()[1:]
    if len(pcms) == 0:
        dialog.ok(xbmcaddon.Addon().getAddonInfo('name'), strings(30210))
        break
    pcmx = dialog.select(strings(30115), pcms)
    if pcmx == -1:
        break
    pcm = pcms[pcmx]
    xbmcaddon.Addon().setSetting('ls_o', pcm)
    break
del dialog
Example #38
0
import alsaaudio as aa
import audioop
from time import sleep
from collections import deque
import time
import select
import sys
import math
import random
import argparse

import unicornhat as unicorn
from UHScroll import *

print(aa.pcms(aa.PCM_CAPTURE))

# Set up audio
data_in = aa.PCM(aa.PCM_CAPTURE, aa.PCM_NONBLOCK, device='default:CARD=Device')
data_in.setchannels(2)
data_in.setrate(44100)
data_in.setformat(aa.PCM_FORMAT_S16_LE)
data_in.setperiodsize(256)

motivations = [
    "Go {0} go!", "Great blows {0}!", "Good effort {0}!",
    "{0}, you're on fire!", "{0} is amazing!", "That was fantastic!",
    "Good progress {0}!", "Physio star {0}!", "Gold star for {0}!",
    "You are doing great {0}!", "Awesome physio {0}!", "Keep it up {0}!",
    "Great work {0}!", "Super strong {0}!", "Your blows are powerful!"
]
Example #39
0
import alsaaudio

print(alsaaudio.pcms())