Beispiel #1
0
def show_mixer(name, kwargs):
    # Demonstrates how mixer settings are queried.
    try:
        mixer = alsaaudio.Mixer(name, **kwargs)
    except alsaaudio.ALSAAudioError:
        print("No such mixer", file=sys.stderr)
        sys.exit(1)

    print("Mixer name: '%s'" % mixer.mixer())
    print("Capabilities: %s %s" % (' '.join(mixer.volumecap()),
                                   ' '.join(mixer.switchcap())))
    volumes = mixer.getvolume()
    for i in range(len(volumes)):
        print("Channel %i volume: %i%%" % (i,volumes[i]))
        
    try:
        mutes = mixer.getmute()
        for i in range(len(mutes)):
            if mutes[i]:
                print("Channel %i is muted" % i)
    except alsaaudio.ALSAAudioError:
        # May not support muting
        pass

    try:
        recs = mixer.getrec()
        for i in range(len(recs)):
            if recs[i]:
                print("Channel %i is recording" % i)
    except alsaaudio.ALSAAudioError:
        # May not support recording
        pass
Beispiel #2
0
 def radio_vol_up(self):
     #		subprocess.check_output(["mpc", "volume", "+5"])
     m = alsaaudio.Mixer('PCM')
     current_volume = m.getvolume()
     if current_volume[0] < 95:
         #			print (current_volume[0])
         m.setvolume(current_volume[0] + 5)
Beispiel #3
0
def set_mixer(name, args, idx=0):
    # Demonstrates how to set mixer settings
    try:
        mixer = alsaaudio.Mixer(name, cardindex=idx)
    except alsaaudio.ALSAAudioError:
        sys.stderr.write("No such mixer")
        sys.exit(1)

    if args.find(',') != -1:
        args_array = args.split(',')
        channel = int(args_array[0])
        args = ','.join(args_array[1:])
    else:
        channel = alsaaudio.MIXER_CHANNEL_ALL

    if args in ['mute', 'unmute']:
        # Mute/unmute the mixer
        if args == 'mute':
            mixer.setmute(1, channel)
        else:
            mixer.setmute(0, channel)

    elif args in ['rec', 'unrec']:
        # Enable/disable recording
        if args == 'rec':
            mixer.setrec(1, channel)
        else:
            mixer.setrec(0, channel)

    else:
        # Set volume for specified channel. MIXER_CHANNEL_ALL means set
        # volume for all channels
        volume = int(args)
        mixer.setvolume(volume, channel)
Beispiel #4
0
    def __init__(self, name, initValue, mixer):
        self.value = DoubleVar()
        self.value.set(initValue)  ###
        self.mixer = alsaaudio.Mixer(mixer)
        Scale.__init__(
            self,
            rootFrame,
            from_=1000,
            to=0,
            length=400,
            sliderlength=20,
            width=8,
            troughcolor='black',
            sliderrelief='flat',
            relief="flat",
            borderwidth=0,
            showvalue=0,
            background="#eee",  #actually slider color
            variable=self.value,
            command=(lambda x: self.changeVolume(x)))

        self.name = name

        self.volume = relinearize(self.value.get())  ###
        self.mixer.setvolume(self.volume)
Beispiel #5
0
 def mixer_changed(self, source=None, condition=None, reopen=True):
     if reopen:
         for audiofader in self.audiofaders:
             audiofader['control'] = alsaaudio.Mixer(
                 control=audiofader['name'])
     self.update_audio()
     return True
Beispiel #6
0
 def __init__(self):
     if alsaaudio:
         self.mixer = alsaaudio.Mixer(control='PCM')
     elif osax:
         self.mixer = osax.OSAX()
     else:
         print "Unable to control volume"
Beispiel #7
0
def init(settings, mix):
    global volume, balance, mute, mixer
    volume = settings["volume"]
    balance = settings["balance"]
    ismute = settings["mute"]
    mixer = alsaaudio.Mixer(mix)
    """
Beispiel #8
0
    async def mute(self, ctx):
        await self.bot.safe_delete(ctx.message)
        permCheck, err = (await self.bot.permissions_hasrole(self, ctx.message.author, "admin"))
        if permCheck:
            m = alsaaudio.Mixer('PCM')
            current_vol = (m.getvolume())[0]
           
            if not (self.bot.ismuted):
                print(Fore.CYAN + "[SOUND][MUTE] " + ctx.message.author.name + " has just muted the speakers" + Style.RESET_ALL)
                # Mute
                await ctx.send(embed=(await self.bot.generate_embed(self, title=":mute: Speakers have been muted", footer=f"From {ctx.message.author.name}")), delete_after=20)
                m.setvolume(0) # Off
                await self.setvol(0) # Off
                self.bot.ismuted = True
                return
            else:
                print(Fore.CYAN + "[SOUND][UNMUTE] " + ctx.message.author.name + " has just unmuted the speakers" + Style.RESET_ALL)
                # Unmute
                await ctx.send(embed=(await self.bot.generate_embed(self, title=":speaker: Speakers have been unmuted", footer=f"From {ctx.message.author.name}")), delete_after=20)
                if not (self.bot.lastVolume == 0):
                    print("[SOUND][MUTE] Going back to lastVolume: " + str(self.bot.lastVolume))
                    m.setvolume(self.bot.lastVolume) # On
                    await self.setvol(self.bot.lastVolume)
                else:
                    print("[SOUND][MUTE] Couldn't get lastVolume, Defaulting to 50")
                    m.setvolume(50) # On
                    await self.setvol(50) # Default
                self.bot.ismuted = False
                return


        else:
            await ctx.send(embed=(await self.bot.generate_error(self, err)), delete_after=20)
        return
Beispiel #9
0
def vol_down():
    m = alsaaudio.Mixer('PCM')
    current_volume = m.getvolume()
    if current_volume[0] > 10:
        #		print (current_volume[0])
        m.setvolume(current_volume[0] - 5)
    return render_template('main.html')
Beispiel #10
0
def get_mixer(name, **kwargs):
    # Demonstrates how mixer settings are queried.
    result = {}
    try:
        mixer = alsaaudio.Mixer(name, **kwargs)
    except alsaaudio.ALSAAudioError:
        print("No such mixer", file=sys.stderr)
        sys.exit(1)

    result['volumecap'] = mixer.volumecap()
    result['switchcap'] = mixer.switchcap()
    result['volumes'] = mixer.getvolume()

    try:
        result['mutes'] = mixer.getmute()
    except alsaaudio.ALSAAudioError:
        # May not support muting
        pass

    try:
        result['recs'] = mixer.getrec()
    except alsaaudio.ALSAAudioError:
        # May not support recording
        pass

    return result
Beispiel #11
0
	def __init__(self):
		
		#gerekli değişkenler oluşturuluyor
		self.panel = None
		self.time_button = None
		self.time_window = None
		self.time_window_showing = False
		self.calendar = None
		self.volume_button = None
		self.sound_window = None
		self.sound_window_showing = False
		self.wifi_button = None
		self.wifi_image = None
		self.wifi_window = None
		self.wifi_window_showing = False
		self.apps_image = None
		self.apps_button = None
		self.apps_window = None
		self.apps_window_showing = False
		self.sound_system = alsaaudio.Mixer()
		self.g_c_year,self.g_c_month,self.g_c_day = None,None,None
		self.activities = []
		
		#pencere düzenleniyor
		self.window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
		self.window.set_type_hint(Gdk.WindowTypeHint.DOCK)
		self.window.set_wmclass("panel","tpanel")
		self.window.move(0,0)
		self.window.set_decorated(False)
		
		#panel oluşturulup düzenleniyor
		self.create_panel_box()
		self.add_plugins_to_panel()
		self.window.add(self.panel)
		self.xstuff()
Beispiel #12
0
 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)
Beispiel #13
0
def updatevol(bs):
    if len(bs) > 1:
        if bs[0] == 0 and bs[2] == 127:
            m = alsaaudio.Mixer()
            newvol = 8 - bs[1]
            newvol = newvol * 12.5
            m.setvolume(int(newvol))
Beispiel #14
0
def vol_dec(dec=3):
    mixer = alsaaudio.Mixer()
    init_vol = int(mixer.getvolume()[0])
    newvolume = init_vol - dec
    if newvolume < 0:
        newvolume = 0
    mixer.setvolume(newvolume)
Beispiel #15
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
Beispiel #16
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)
Beispiel #17
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)
Beispiel #18
0
def raise_volume():
    m = alsaaudio.Mixer()
    current_volume = m.getvolume()
    #print("Current volume is ", current_volume)
    next_volume=current_volume[0]+25 if current_volume[0] < 75 else 100
    #print("Next volume is ",next_volume)
    m.setvolume(next_volume)
Beispiel #19
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)
Beispiel #20
0
def vol_inc(inc=3):
	mixer=alsaaudio.Mixer()
	init_vol=int(mixer.getvolume()[0])
	newvolume=init_vol+inc
	if newvolume >100 :
		newvolume=100
	mixer.setvolume(newvolume)
    def getFormato(self):
        readVol = 100 - int(sensorVol.distance * 100)
        m = alsaaudio.Mixer('HDMI')
        current_volume = m.getvolume()
        m.setvolume(readVol)
        self.volProg['value']=readVol
        if(self.formatoAtual=="senoidal"):
            read = sensorFreq.distance * highestNote
            print(read)
            a = Sine(mul=5, freq=read).out()
            self.freqRead['text'] = int(read)
            sleep(0.1)
           
        elif(self.formatoAtual=="quadrada"):
            read = sensorFreq.distance * highestNote
            print(read)
            freq = [read * i for i in range(1,high) if i%2 == 1]
            harm = [0.33 / i for i in range(1,high) if i%2 == 1]
            a = Sine(mul=harm,freq=read).out()
            self.freqRead['text'] = int(read)
            sleep(0.1)

        else:
            read = sensorFreq.distance * highestNote
            print(read)
            a = SuperSaw(mul=5, freq=read).out()
            self.freqRead['text'] = int(read)
            sleep(0.1)
Beispiel #22
0
def show_mixer(name, idx=0):
    # Demonstrates how mixer settings are queried.
    try:
        mixer = alsaaudio.Mixer(name, cardindex=idx)
    except alsaaudio.ALSAAudioError:
        sys.stderr.write("No such mixer\n")
        sys.exit(1)

    sys.stdout.write("Mixer name: '%s'\n" % mixer.mixer())
    sys.stdout.write(
        "Capabilities: %s %s\n" %
        (' '.join(mixer.volumecap()), ' '.join(mixer.switchcap())))
    volumes = mixer.getvolume()
    for i in range(len(volumes)):
        sys.stdout.write("Channel %i volume: %i%%\n" % (i, volumes[i]))

    try:
        mutes = mixer.getmute()
        for i in range(len(mutes)):
            if mutes[i]:
                sys.stdout.write("Channel %i is muted\n" % i)
    except alsaaudio.ALSAAudioError:
        # May not support muting
        pass

    try:
        recs = mixer.getrec()
        for i in range(len(recs)):
            if recs[i]:
                sys.stdout.write("Channel %i is recording\n" % i)
    except alsaaudio.ALSAAudioError:
        # May not support recording
        pass
Beispiel #23
0
def main():
    while True:
        record()
        try:
            text = recognize_audio_file()
            print(text)
            if text.strip() == "play music":
                speak("Which song you want to play?")
                record(seconds=5)
                try:
                    text = recognize_audio_file()
                    speak(f'Finished recording. Playing {text}')
                    play_music(text)

                except sr.UnknownValueError:
                    speak(
                        'I didn\'t recognise the text. Say play music if you want to play music'
                    )

            if text.strip() == 'stop':
                speak("I'm outta here")
                break

            if ''.join(text.strip().split()[:2]) == 'setvolume':
                m = alsaaudio.Mixer()
                current_volume = m.getvolume()
                m.setvolume(int(text.strip().split()[-1]))

        except sr.UnknownValueError:
            continue
Beispiel #24
0
    def VolumeUp(self):
        m = alsaaudio.Mixer()
        vol = m.getvolume()[0]

        #       print("VolumeUp vol %d " % vol)
        for i, v in enumerate(self.snd_segs):
            if vol >= v[0] and vol <= v[1]:
                self._Needle = i
                break

        self._Needle += 1

        if self._Needle > len(self.snd_segs) - 1:
            self._Needle = len(self.snd_segs) - 1

#        print("Set volume %d" % self.snd_segs[self._Needle][1] )
        m.setvolume(
            self.snd_segs[self._Needle][0] +
            (self.snd_segs[self._Needle][1] - self.snd_segs[self._Needle][0]) /
            2)  ## prefer bigger one

        self._Value = self.snd_segs[self._Needle][1]

        #        print( self._Value)
        return self._Value
Beispiel #25
0
    def run(self):
        # try:
        card_index = DharmacorderSettings.instance.recording_device_number
        mixer_control = "Mic"
        volume_level = DharmacorderSettings.instance.recording_gain_0_to_100

        mixer = alsaaudio.Mixer(control=mixer_control, cardindex=card_index)
        mixer.setvolume(volume_level, 0, 'capture')
        # pcm = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK, str(card_index))
        pcm = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL,
                            str(card_index))
        pcm.setchannels(2)
        pcm.setrate(48000)

        # warning:  setperiodsize is ineffective.  It's always 1024.
        # for n in range(1, 16385):
        #     if pcm.setperiodsize(n) == n:
        #         print n

        pcm.setformat(alsaaudio.PCM_FORMAT_S16_LE)
        pcm.setperiodsize(1024)
        while self._state.still_recording and not self.maximum_record_seconds_reached:
            l, data = pcm.read()
            # print l
            if l < 0:
                print "Overrun!  Skipping this read"
            else:
                self._state._state_machine.wavefile.writeframes(data)
        self.transition_away()
Beispiel #26
0
 def SyncSoundVolume(self):
     try:
         m = alsaaudio.Mixer()
         vol = m.getvolume()[0]
     except Exception, e:
         print(str(e))
         vol = 0
Beispiel #27
0
 def radio_vol_down(self):
     #		subprocess.check_output(["mpc", "volume", "-5"])
     m = alsaaudio.Mixer('PCM')
     current_volume = m.getvolume()
     if current_volume[0] > 10:
         #			print (current_volume[0])
         m.setvolume(current_volume[0] - 5)
    def __init__(self):

        # create sounds cache folder if it does not exist
        self.sounds_cache_path = "%s/sounds" % CACHE_PATH
        Path(self.sounds_cache_path).mkdir(parents=True, exist_ok=True)

        self.mqttc = mqtt.Client("hmi-audio")

        self.mqttc.on_connect = self.on_connect
        self.mqttc.on_message = self.on_message

        self.mqttc.username_pw_set(config['mqtt']['username'],
                                   config['mqtt']['password'])
        self.mqttc.connect(config['mqtt']['host'])

        # set a default volume
        self.master_volume = 30

        # volume set requests are generally set as retain
        # we do not want to announce a volume change on start of this script
        self.volume_is_set = False

        # Initialize USB Sound Card - Remove Mute and set volume to 100%
        # troubleshoot: aplay -l
        # Onboard sound card is cardindex=0
        # HACK TO FIND THE CARD! C-Media USB Sound card has a mixer
        #  called "Auto Gain Control"
        cardindex = None
        cards = alsa.cards()
        for i in range(len(cards)):
            mixers = alsa.mixers(cardindex=i)
            for control in mixers:
                if control == "Auto Gain Control":
                    cardindex = i
        if cardindex is None:
            print("unable to find soundcard!")
            exit()

        # Set Mute OFF and device volume to 100%
        self.device_mixer = alsa.Mixer(control="Speaker", cardindex=cardindex)
        self.device_mixer.setmute(0)
        self.device_mixer.setvolume(100)

        # unmute master mixer and set volume to default
        self.master_mixer = alsa.Mixer(control="Master")
        self.master_mixer.setmute(0)
        self.master_mixer.setvolume(self.master_volume)
Beispiel #29
0
	def initializeParameters(self):

		with open( './.pathToATPlatform' ,'r' ) as textFile:
			self.pathToATPlatform = textFile.readline( )
		    
		with open( self.pathToATPlatform + 'parameters', 'r' ) as parametersFile:
			for line in parametersFile:

				if line[ :line.find('=')-1 ] == 'timeGap':
					self.timeGap = int( line[ line.rfind('=')+2:-1 ] )
				elif line[ :line.find('=')-1 ] == 'backgroundColour':
					self.backgroundColour = line[ line.rfind('=')+2:-1 ]
				elif line[ :line.find('=')-1 ] == 'textColour':
					self.textColour = line[ line.rfind('=')+2:-1 ]
				elif line[ :line.find('=')-1 ] == 'scanningColour':
					self.scanningColour = line[ line.rfind('=')+2:-1 ]
				elif line[ :line.find('=')-1 ] == 'selectionColour':
					self.selectionColour = line[ line.rfind('=')+2:-1 ]
				elif line[ :line.find('=')-1 ] == 'filmVolume':
					self.filmVolumeLevel = int( line[ line.rfind('=')+2:-1 ] )
				elif line[ :line.find('=')-1 ] == 'musicVolume':
					self.musicVolumeLevel = int( line[ line.rfind('=')+2:-1 ] )
					
				elif not line.isspace( ):
					print 'Niewłaściwie opisane parametry'
					print 'Błąd w linii', line
					
					self.timeGap = 1500
					self.backgroundColour = 'white'
					self.textColour = 'black'
					self.scanningColour =  '#E7FAFD'
					self.selectionColour = '#9EE4EF'
					self.filmVolumeLevel = 100
					self.musicVolumeLevel = 70
					
		alsaaudio.Mixer( control = 'Master' ).setvolume( self.musicVolumeLevel, 0 )
		self.flag = 'row'

		self.numberOfRows = 4,
		self.numberOfColumns = 5,
            
		self.columnIteration = 0
		self.rowIteration = 0						
		self.panelIteration = 0
		self.emptyColumnIteration = 0
		self.emptyRowIteration = 0
		self.emptyPanelIteration = 0
		self.maxEmptyColumnIteration = 2									
		self.maxEmptyRowIteration = 2									
		self.maxEmptyPanelIteration = 2

		self.numberOfPresses = 1

		self.mouseCursor = PyMouse( )
		self.mousePosition = self.winWidth - 8, self.winHeight - 8
               	self.mouseCursor.move( *self.mousePosition )			

		self.radioFlag = 'OFF'
		self.SetBackgroundColour( 'black' )
Beispiel #30
0
 def setVolume(self, volume: int):
     try:
         mixer = alsaaudio.Mixer(self.__name, **self.__kwargs)
         channel = alsaaudio.MIXER_CHANNEL_ALL
         mixer.setmute(0, channel)
         mixer.setvolume(volume, channel)
     except alsaaudio.ALSAAudioError as e:
         raise AlsaError(str(e))