Skip to content

Instantly share code, notes, and snippets.

@marcusscomputer
Created April 26, 2021 19:48
Show Gist options
  • Save marcusscomputer/84483c64b79352e012143c48058af681 to your computer and use it in GitHub Desktop.
Save marcusscomputer/84483c64b79352e012143c48058af681 to your computer and use it in GitHub Desktop.
A modified test_microphone.py example script to do something in Elite Dangerous - can be adjusted to do just about anything you want.
#!/usr/bin/env python3
import argparse
import os
import queue
import sounddevice as sd
import vosk
import sys
import json
import subprocess
q = queue.Queue()
def int_or_str(text):
"""Helper function for argument parsing."""
try:
return int(text)
except ValueError:
return text
def callback(indata, frames, time, status):
"""This is called (from a separate thread) for each audio block."""
if status:
print(status, file=sys.stderr)
q.put(bytes(indata))
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
'-l', '--list-devices', action='store_true',
help='show list of audio devices and exit')
args, remaining = parser.parse_known_args()
if args.list_devices:
print(sd.query_devices())
parser.exit(0)
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[parser])
parser.add_argument(
'-f', '--filename', type=str, metavar='FILENAME',
help='audio file to store recording to')
parser.add_argument(
'-m', '--model', type=str, metavar='MODEL_PATH',
help='Path to the model')
parser.add_argument(
'-d', '--device', type=int_or_str,
help='input device (numeric ID or substring)')
parser.add_argument(
'-r', '--samplerate', type=int, help='sampling rate')
args = parser.parse_args(remaining)
try:
if args.model is None:
args.model = "model"
if not os.path.exists(args.model):
print ("Please download a model for your language from https://alphacephei.com/vosk/models")
print ("and unpack as 'model' in the current folder.")
parser.exit(0)
if args.samplerate is None:
device_info = sd.query_devices(args.device, 'input')
# soundfile expects an int, sounddevice provides a float:
args.samplerate = int(device_info['default_samplerate'])
model = vosk.Model(args.model)
if args.filename:
dump_fn = open(args.filename, "wb")
else:
dump_fn = None
with sd.RawInputStream(samplerate=args.samplerate, blocksize = 8000, device=args.device, dtype='int16', channels=1, callback=callback):
#print('#' * 80)
#print('Press Ctrl+C to stop the recording')
#print('#' * 80)
rec = vosk.KaldiRecognizer(model, args.samplerate)
while True:
data = q.get()
if rec.AcceptWaveform(data):
# Get JSON
vc = json.loads(rec.Result())
# Do something with the detected text:
# ELITE DANGEROUS
if vc['text'] == "navigation":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "1"])
if vc['text'] == "communications":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "2"])
if vc['text'] == "crew":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "3"])
if vc['text'] == "systems":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "4"])
if vc['text'] == "select":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "space"])
if vc['text'] == "confirm":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "space"])
if vc['text'] == "return":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "BackSpace"])
if vc['text'] == "cancel":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "BackSpace"])
if vc['text'] == "jump":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "j"])
if vc['text'] == "engage":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "j"])
if vc['text'] == "super cruise":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "j"])
if vc['text'] == "down":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "Down"])
if vc['text'] == "up":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "Up"])
if vc['text'] == "left":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "Left"])
if vc['text'] == "right":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "Left"])
if vc['text'] == "spectrum scanner":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "F4"])
if vc['text'] == "f s s":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "F4"])
if vc['text'] == "landing gear":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "l"])
if vc['text'] == "orbits":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "o"])
if vc['text'] == "system map":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "5"])
if vc['text'] == "galaxy map":
subprocess.run(["/home/marcus-s/Private/Scripts/keypress.sh", "6"])
#else:
#print(rec.PartialResult())
if dump_fn is not None:
dump_fn.write(data)
except KeyboardInterrupt:
#print('\nDone')
parser.exit(0)
except Exception as e:
parser.exit(type(e).__name__ + ': ' + str(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment