“author”: “zthxxx”,
“gender”: “female”,
“locale”: “jp”,
“contributes”: [
{
“keywords”: [
“function”,
“=>”
],
“voices”: [
“function_01.mp3”,
“function_02.mp3”,
“function_03.mp3”
]
},
…
]
}
对Java来说,定义两个bean类,解析json即可:
/**
- 加载配置
*/
public static void loadConfig() {
try {
//
FartSettings settings = FartSettings.getInstance();
if (!setting 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 s.isEnable()) {
return;
}
String json = readVoicePackageJson(“manifest.json”);
Gson gson = new Gson();
Manifest manifest = gson.fromJson(json, Manifest.class);
// load contributes.json
if (manifest.getContributes() == null) {
String contributesText = readVoicePackageJson(“contributes.json”);
Manifest contributes = gson.fromJson(contributesText, Manifest.class);
if (contributes.getContributes() != null) {
manifest.setContributes(contributes.getContributes());
}
}
Context.init(manifest);
} catch (IOException e) {
}
}
[](()监控用户输入
=========================================================================
自定义一个Handler类继承TypedActionHandlerBase即可,需要实现的方法原型是:
public void execute(@NotNull Editor editor, char charTyped, @NotNull DataContext dataContext)
chartTyped就是输入的字符,我们可以简单粗暴的将这些组合到一起即可,用一个list缓存,然后将拼接后的字符串匹配关键词。
private List candidates = new ArrayList<>();
@Override
public void execute(@NotNull Editor editor, char charTyped, @NotNull DataContext dataContext) {
candidates.add(String.valueOf(charTyped));
String str = StringUtils.join(candidates, “”);
try {
List voices = Context.getCandidate(str);
if (!voices.isEmpty()) {
Context.play(voices);
candidates.clear();
}
}catch (Exception e){
// TODO
candidates.clear();
}
if (this.myOriginalHandler != null) {
this.myOriginalHandler.execute(editor, charTyped, dataContext);
}
}
匹配关键词更简单,将读取出来的json,放到hashmap中,然后遍历map,如果包含关键词就作为语音候选:
public static List getCandidate(String inputHistory) {
final List candidate = new ArrayList<>();
FartSettings settings = FartSettings.getInstance();
if (!settings.isEnable()) {
return candidate;
}
if (keyword2Voices != null) {
keyword2Voices.forEach((keyword, voices) -> {
if (inputHistory.contains(keyword)) {
candidate.addAll(voices);
}
});
}
if (candidate.isEmpty()) {
candidate.addAll(findSpecialKeyword(inputHistory));
}
return candidate;
}
如果找到候选,就播放。
[](()播放
=====================================================================
为了防止同时播放多个语音,我们用一个单线程线程池来搞定。播放器使用javazoom.jl.player.Player
/**
- play in a single thread pool
*/
static ExecutorService playerTheadPool;
static {
ThreadFactory playerFactory = new ThreadFactoryBuilder()
.setNameFormat(“player-pool-%d”).build();
playerTheadPool = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1024), playerFactory, new ThreadPoolExecutor.AbortPolicy());
}