战舰游戏集成Pocket Sphinx语音识别:自定义字典添加数字发音方法
Hey there! I’ve worked with Pocket Sphinx for custom voice commands before, so let’s get your battleship game’s coordinate recognition sorted out. Since you need to catch terms like A8 without Google’s API, building a custom dictionary and tweaking the language model is the perfect approach. Here’s how to do it step by step:
Pocket Sphinx relies on a .dic file for custom vocabulary. Each line follows this simple structure:
WORD PRONUNCIATION
For your 10x10 grid, you’ll need entries for letters (A-J) and numbers (0-10). You can either recognize individual components (like "A" + "8") and combine them in code, or add combined terms like A8 directly to the dictionary. The first approach is more flexible (no need to add 100 separate coordinate entries), so we’ll focus on that first.
Grab the standard CMU-style phonetic pronunciations for numbers (tweak them if they don’t match how you/players say them). Add these lines to your .dic file:
0 ZIYROH 1 WAHN 2 TOO 3 TH R IY 4 F AO R 5 F AY V 6 S IH K S 7 S EH V AH N 8 EY T 9 N AY N 10 T EH N
If a number is misrecognized frequently, you can add alternative pronunciations separated by a pipe:
8 EY T | AY T
Don’t forget the grid letters! Add these entries to your .dic file too:
A EY B B IY C S IY D D IY E IY F EH F G J IY H EY CH I AY J J EY
To help Pocket Sphinx predict valid coordinate sequences (like letter + number), create a simple grammar file (.gram) instead of a full language model—it’s easier for small, targeted vocabularies. Here’s an example:
#JSGF V1.0; grammar battleship; public <coordinate> = <letter> <number>; <letter> = A | B | C | D | E | F | G | H | I | J; <number> = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
Compile this grammar to a .lm file using Pocket Sphinx’s built-in tool:
sphinx_jsgf2lm -f battleship.gram -o battleship.lm
Now configure Pocket Sphinx to use your custom files in your game code. Here’s a minimal example to get you started:
from pocketsphinx import LiveSpeech # Replace these paths with where you saved your files custom_dic = "./battleship.dic" custom_lm = "./battleship.lm" # Initialize live speech recognition speech = LiveSpeech( dic=custom_dic, lm=custom_lm, verbose=False ) # Process recognized speech for phrase in speech: recognized = str(phrase).strip() print(f"Heard: {recognized}") # Split into letter and number (e.g., "A 8" -> ("A", "8")) parts = recognized.split() if len(parts) == 2: letter, num = parts coordinate = f"{letter}{num}" print(f"Valid coordinate detected: {coordinate}") # Add your game logic here (e.g., check if the coordinate is a hit)
Play around with the recognition—if certain terms are missed, adjust the phonetic pronunciations in your .dic file. For example, if "J" is often misrecognized, try swapping its pronunciation to JH EY instead of J EY.
内容的提问来源于stack exchange,提问作者jejegoodgame

