1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#include <iostream> #include <string> #include <unordered_map> #include <algorithm> class SpeechRecognition { private: std::unordered_map<std::string, std::string> commands; public: SpeechRecognition() { // Initialize with some commands commands["play"] = "Playing music"; commands["stop"] = "Stopping music"; commands["pause"] = "Pausing music"; commands["resume"] = "Resuming music"; } void recognizeSpeech(const std::string& input) const { std::string command = input; std::transform(command.begin(), command.end(), command.begin(), ::tolower); // Convert to lowercase auto it = commands.find(command); if (it != commands.end()) { std::cout << it->second << std::endl; } else { std::cout << "Command not recognized" << std::endl; } } }; int main() { SpeechRecognition sr; std::cout << "Speak a command (e.g., play, stop, pause, resume):" << std::endl; while (true) { std::string input; std::getline(std::cin, input); if (input == "exit") { break; } sr.recognizeSpeech(input); } return 0; } |
Explanation
- Class Definition:
SpeechRecognition
class simulates the functionality of speech recognition.- It contains a private member
commands
, which is anunordered_map
that maps recognized commands (strings) to their responses (also strings).
- Constructor:
- Initializes the
commands
map with a few predefined commands and their corresponding actions.
- Initializes the
- Member Function:
recognizeSpeech(const std::string& input) const
:- Converts the input command to lowercase to ensure case-insensitivity.
- Searches for the command in the
commands
map. - Prints the corresponding action if found; otherwise, prints “Command not recognized”.
- Main Function:
- Creates an instance of
SpeechRecognition
. - Prompts the user to input commands.
- Reads user input and uses the
recognizeSpeech
method to process and respond to the command. - Allows the user to exit the program by typing “exit”.
- Creates an instance of