<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/perl

package SpeechRecognition;
use JSON::Parse 'parse_json';
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(interpret_from_mic interpret_from_file);

our $VERSION = 0.1;



# Define constants
my $API_ADDRESS = "http://www.google.com/speech-api/v1/recognize?lang=en";
my $RECORD_COMMAND = "arecord -q -f cd -t wav -d 3 -r 16000 | flac - -f -s --best --sample-rate 16000 -o /dev/shm/rectmp.flac";
  
my $SEARCH_FOR_ARRAY_KEY = "hypotheses";
my $SEARCH_FOR_HASH_KEY = "utterance";
my $FILE_REMOVE_COMMAND = "rm /dev/shm/rectmp.flac";


sub interpret_from_mic {
    if ($_[0] != 0) {$RECORD_COMMAND =  "arecord -q -f cd -t wav -d $_[0] -r 16000 | flac - -f -s --best --sample-rate 16000 -o /dev/shm/rectmp.flac";}
    my $QUERY_COMMAND = "wget -O - -o /dev/null --post-file /dev/shm/rectmp.flac --header=\"Content-Type: audio/x-flac; rate=16000\" $API_ADDRESS";
    qx($RECORD_COMMAND);
    my $jsonReceived = qx($QUERY_COMMAND);
    #  print("$jsonReceived\n");
    my $parsedJSON = parse_json ($jsonReceived);
    my $arrayRef = $parsedJSON-&gt;{$SEARCH_FOR_ARRAY_KEY};
    my $hashRef = $ { $arrayRef }[0];
    my $spokenText = $ { $hashRef } { $SEARCH_FOR_HASH_KEY };
    system("$FILE_REMOVE_COMMAND");
    $spokenText;
}

sub interpret_from_file {
    my $QUERY_COMMAND = "wget -O - -o /dev/null --post-file $_[0] --header=\"Content-Type: audio/x-flac; rate=16000\" $API_ADDRESS";
    
    my $jsonReceived = qx($QUERY_COMMAND);
    #  print("$jsonReceived\n");
    my $parsedJSON = parse_json ($jsonReceived);
    my $arrayRef = $parsedJSON-&gt;{$SEARCH_FOR_ARRAY_KEY};
    my $hashRef = $ { $arrayRef }[0];
    my $spokenText = $ { $hashRef } { $SEARCH_FOR_HASH_KEY };
    $spokenText;
}

</pre></body></html>