Last active
September 10, 2017 13:02
-
-
Save lucianogiuseppe/6ed04eea5d5c276aafa5a4e9c0fcd9c4 to your computer and use it in GitHub Desktop.
Script per automatizzare il processo di ascolto del Vinile sul bluetooth via RaspberryPi o altri Linux device
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bluetooth | |
from bluetoothctl import BluetoothctlError, Bluetoothctl #Python3: fix Exceptions syntax | |
import subprocess | |
import time | |
import pulsectl | |
def setOutAudio(bName): | |
try: | |
with pulsectl.Pulse() as pulse: | |
for sink in pulse.sink_list(): | |
if sink.description==bName: | |
pulse.sink_default_set(sink) | |
return | |
except Exception as e: | |
print(e) | |
def connetti(addr, bName): | |
try: | |
bctl = Bluetoothctl() | |
print(bctl.get_output('power on',1)) | |
print(bctl.get_output('agent on',1)) | |
print(bctl.get_output('default-agent',1)) | |
print(bctl.get_output('scan on',4)) | |
print(bctl.get_output('scan off',1)) | |
#giusto per sicurezza | |
print(bctl.get_output("disconnect %s"%(addr),4)) | |
print(bctl.get_output("trust %s"%addr,2)) | |
print(bctl.get_output("pair %s"%addr,2)) | |
print(bctl.get_output("connect %s"%addr,4)) | |
subprocess.call(['pulseaudio', '-D']) | |
setOutAudio(bName) | |
try: | |
arecord = subprocess.Popen(['arecord', '-D', 'plughw:1,0','-f','dat'], stdout=subprocess.PIPE) | |
subprocess.check_output(['aplay', '-f', 'dat'], stdin=arecord.stdout) | |
arecord.wait() | |
except KeyboardInterrupt: | |
arecord.terminate() | |
except Exception as e: | |
print(e) | |
print(bctl.get_output("remove %s"%addr,4)) | |
print(bctl.get_output("quit")) | |
except BluetoothctlError as e: | |
print(e) | |
if __name__ == "__main__": | |
print("Searching devices...") | |
nearby_devices = bluetooth.discover_devices( | |
duration=8, lookup_names=True, flush_cache=True) | |
print("found %d devices" % len(nearby_devices)) | |
if len(nearby_devices) > 0: | |
print("Connecting to first device") | |
for addr, name in nearby_devices: | |
try: | |
print(" %s - %s" % (addr, name)) | |
connetti(addr, name) | |
break | |
except UnicodeEncodeError: | |
print(" %s - %s" % (addr, name.encode('utf-8', 'replace'))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment