Getting list of audio Input devices in Python - python-2.7

How do I get the list of audio input devices in linux using python in this format as hw:0,1 ?
I've tried the following using pyaudio :
def getaudiodevices():
p = pyaudio.PyAudio()
print p.get_default_input_device_info()
for i in range(p.get_device_count()):
print ''#p.get_device_info_by_index(i)
I'm also able to retrieve using "arecord -l" but I need to just get it like
hw:0,1
hw:0,2
I need it in this format. Do you have any suggestions?
Thanks.

If the name stored by the PaDeviceInfo structure is sufficient, then you could just access the 'name' from the dict returned by get_device_info_by_index(), and then perhaps slice the information off the end:
import pyaudio
def getaudiodevices():
p = pyaudio.PyAudio()
for i in range(p.get_device_count()):
print p.get_device_info_by_index(i).get('name')
gives me
HDA Intel HDMI: 0 (hw:0,3)
HDA Intel HDMI: 1 (hw:0,7)
HDA Intel HDMI: 2 (hw:0,8)
HDA Intel PCH: CS4208 Analog (hw:1,0)
HDA Intel PCH: CS4208 Digital (hw:1,1)
hdmi
default
But this doesn't give you what you want with the default devices, the name seems to be stored as "default". In that case, executing "arecord -l" in Python can work, if that's what you're looking for. Of course, you can do the same thing for "aplay -l".
import os
def getaudiodevices():
devices = os.popen("arecord -l")
device_string = devices.read()
device_string = device_string.split("\n")
for line in device_string:
if(line.find("card") != -1):
print "hw:" + line[line.find("card")+5] + "," +\
line[line.find("device")+7]
outputs
hw:1,0

Related

How to send ascii characters through serial in python?

I want to send 3 numbers (integers) through serial port in ascii format. I use putty terminal to see the receiving data on the other end. The problem is that putty doesn't shows anything except strings. I tried to use the ord() function to get the ascii format but I cannot see anything on putty. Is it just a putty problem with ascii format, or I don't send data at all? How can I be sure that I send the data in the correct format (ascii)?
I am new to python, so sorry if this sounds trivial.
I use Ubuntu 16.04 LTS and Python 2.7.12.
Thank you in advance!
#!/opt/bin/python
import serial
import time
camera = [0, 0, 0]
ser = serial.Serial('/dev/ttyUSB0', 9600)
print (ser.name)
print ("Port Open")
time.sleep(2)
while ser.isOpen():
for i in range(1):
#ser.write(b'5')
#ser.write(chr(5))
#ser.write(5)
ser.write(ord(str(camera[0])))
#ser.write(bytes(camera))
print(camera)
time.sleep(1)
camera[1] = camera[1] + 1
ser.close()

Programmatically Connect to Wifi device python Raspberry

I am working with Raspberry PI 3.
Here I have a task to create Custom GUI to view all the available wifi connections and to connect selected wifi using python.
I am able to get all the Wifi connections through following code.
import subprocess
results = subprocess.check_output(["netsh", "wlan", "show", "network"])
print(results)
results = results.decode("ascii") # needed in python 3
results = results.replace("\r","")
ls = results.split("\n")
ls = ls[4:]
ssids = []
x = 0
while x < len(ls):
if x % 5 == 0:
ssids.append(ls[x])
x += 1
#print(ssids)
But, I am not able to get apis to connect to particular wifi.
Kindly provide me good tutorial for that If any.
Thank you guys

How to get MAC address of connected Access point?

I am using Scapy to sniff access point(AP) beacon packets and also getting all AP beacon packets and it's MAC address nearby AP but I need exact MAC address of connected AP then How to sniff only connected AP beacon frame or How to filter connected AP beacon frame using scapy or any alternate idea.
*I am doing it in python 2.7
Assuming the beacon frame is called pkt. pkt.addr1 is the destination MAC, pkt.addr2 is the source MAC and pkt.addr3 is the MAC address of the AP. You could write something like:
from scapy.all import *
def ap_mac(pkt):
if pkt.haslayer(Dot11)
if pkt.type == 0 and pkt.subtype == 8:
print('SSID: '+%s+' MAC:'+%s)(pk.info,pkt.addr3)
else: pass
else: pass
sniff(prn=ap_mac)
to print out all the AP MACs from beacon frames. Then you could use something like:
from scapy.all import *
def sniff_ap(pkt):
if pkt.haslayer(Dot11):
if pkt.add3 == 'xx.xx.xx.xx.xx.xx': ## AP MAC
print(pkt.summary())
else: pass
else: pass
sniff(prn=sniff_ap)
Here is a good link re: beacon frames. https://www.4armed.com/blog/forging-wifi-beacon-frames-using-scapy/
I choose alternate method i.e using command in python program
Code snippet
def Check_connected_ap():
cmd =["nmcli -f BSSID,ACTIVE dev wifi list | awk '$2 ~ /yes/ {print $1}'"]
address = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(out, err) = address.communicate()
print out

Python on Raspberry Pi: results are only integers

I am using the following python code on the Raspberry Pi to collect an audio signal and output the volume. I can't understand why my output is only integer.
#!/usr/bin/env python
import alsaaudio as aa
import audioop
# Set up audio
data_in = aa.PCM(aa.PCM_CAPTURE, aa.PCM_NONBLOCK, 'hw:1')
data_in.setchannels(2)
data_in.setrate(44100)
data_in.setformat(aa.PCM_FORMAT_S16_LE)
data_in.setperiodsize(256)
while True:
# Read data from device
l,data = data_in.read()
if l:
# catch frame error
try:
max_vol=audioop.max(data,2)
scaled_vol = max_vol/4680
if scaled_vol==0:
print "vol 0"
else:
print scaled_vol
except audioop.error, e:
if e.message !="not a whole number of frames":
raise e
Also, I don't understand the syntax in this line:
l,data = data_in.read()
It's likely that it's reading in a byte. This line l,data = data_in.read() reads in a tuple (composed of l and data). Run the type() builtin function on those variables and see what you've got to work with.
Otherwise, look into the documentation for PCM Terminology and Concepts located within the documentation for the pyalsaaudio package, located here.

pygame initialize framebuffer or x server

I have a class that checks for suitable framebuffer, and it works fine. One a couple of computers (mostly embedded older boards) there is no framebuffer, so I remove the init(self): function and manually set it to run under X. Both ways work on their respective systems, I'm just tired of porting it every time I make a change.
Here is the working framebuffer code:
class wxdisplay :
screen = None;
def __init__(self):
"Ininitializes a new pygame screen using the framebuffer"
# Based on "Python GUI in Linux frame buffer"
# http://www.karoltomala.com/blog/?p=679
disp_no = os.getenv("DISPLAY")
if disp_no:
print "I'm running under X display = {0}".format(disp_no)
# Check which frame buffer drivers are available
# Start with fbcon since directfb hangs with composite output
drivers = ['fbcon', 'directfb', 'svgalib']
found = False
for driver in drivers:
# Make sure that SDL_VIDEODRIVER is set
if not os.getenv('SDL_VIDEODRIVER'):
os.putenv('SDL_VIDEODRIVER', driver)
try:
pygame.display.init()
except pygame.error:
print 'Driver: {0} failed.'.format(driver)
continue
found = True
break
if not found:
raise Exception('No suitable video driver found!')
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
print "Framebuffer size: %d x %d" % (size[0], size[1])
self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)class wxdisplay :
And here is the non-framebuffered version:
class wxdisplay :
pygame.init()
size = (1024, 768)
screen = pygame.display.set_mode(size)
print "Framebuffer size: %d x %d" % (size[0], size[1])
I would like to try and initialize the framebuffer and if it fails, try and just run it on the console. Every thing I have try'd or if'd or excepted fails...
class wxdisplay :
def __init__(self):
# Try to use framebuffer, and use the local X server if not there
try:
screen = None;
"Ininitializes a new pygame screen using the framebuffer"
# Based on "Python GUI in Linux frame buffer"
# http://www.karoltomala.com/blog/?p=679
disp_no = os.getenv("DISPLAY")
print("disp_no " +disp_no)
if disp_no:
print "I'm running under X display = {0}".format(disp_no)
# Check which frame buffer drivers are available
# Start with fbcon since directfb hangs with composite output
drivers = ['fbcon', 'directfb', 'svgalib', 'xvfb', 'Xvfb']
found = False
for driver in drivers:
# Make sure that SDL_VIDEODRIVER is set
if not os.getenv('SDL_VIDEODRIVER'):
os.putenv('SDL_VIDEODRIVER', driver)
try:
print("Driver: "+driver)
pygame.display.init()
except pygame.error:
print 'Driver: {0} failed.'.format(driver)
continue
found = True
print("break")
break
if not found:
raise Exception('No suitable video driver found!')
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
print "Framebuffer size: %d x %d" % (size[0], size[1])
self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
except:
print('No suitable Framebuffer found!')
pygame.init()
size = (1024, 768)
print "X server size: %d x %d" % (size[0], size[1])
self.screen = pygame.display.set_mode(size)
fails with:
starting from __main__ call
disp_no localhost:11.0
I'm running under X display = localhost:11.0
Driver: fbcon
Driver: fbcon failed.
Driver: directfb
commandline read: python
commandline read: ./PiWxDisplay.py
~~~~~~~~~~~~~~~~~~~~~~~~~~| DirectFB 1.2.10 |~~~~~~~~~~~~~~~~~~~~~~~~~~
(c) 2001-2008 The world wide DirectFB Open Source Community
(c) 2000-2004 Convergence (integrated media) GmbH
----------------------------------------------------------------
(*) DirectFB/Core: Single Application Core. (2012-05-20 13:17)
(!) Direct/Util: opening '/dev/fb0' and '/dev/fb/0' failed
--> No such file or directory
(!) DirectFB/FBDev: Error opening framebuffer device!
(!) DirectFB/FBDev: Use 'fbdev' option or set FRAMEBUFFER environment variable.
(!) DirectFB/Core: Could not initialize 'system_core' core!
--> Initialization error!
Driver: directfb failed.
Driver: svgalib
Driver: svgalib failed..
No suitable Framebuffer found!
X server size: 1024 x 768
Traceback (most recent call last):
File "./PiWxDisplay.py", line 366, in <module>
wxdisplay().start_screen()
File "./PiWxDisplay.py", line 66, in __init__
self.screen = pygame.display.set_mode(size)
pygame.error: No available video device
I obviously don't fully understand how to initialize pygame correctly. How would I get it to
Check for a FB driver
Use the X server if the FB driver detection fails
Late answer but I wish I would have tried that earlier :
You may need to be root to use a frame buffer driver.
(It helped in my case: RaspberryPi 2 without X running but with a screen connected. I can now open a display through SSH or directly on the RPi)
You have already changed the SDL_VIDEODRIVER environment to check only for fb devices.
I'd suggest using this before your pygame.init() call in your exception handler:
os.putenv('SDL_VIDEODRIVER', 'x11')
or unset the SDL_VIDEODRIVER environment var, so that pygame.init() doesn't think it's already dealt with.
see: http://www.pygame.org/docs/ref/display.html#pygame.display.init