示例

import $ from 'jquery';
const tf = require('@tensorflow/tfjs');
const speechCommands = require('@tensorflow-models/speech-commands');
const  MODEL_PATH='http://127.0.0.1:8080/speech';

$(async ()=>{
  //创建语音识别器
  const recognizer=speechCommands.create(
    'BROWSER_FFT',
    null,
    MODEL_PATH+'/model.json',
    MODEL_PATH+'/metadata.json'
  );

  //加载模型
  await recognizer.ensureModelLoaded();
  
  //查看可识别单词
  const labels=recognizer.wordLabels()
  console.log(labels);

  //创建标签
  const element=document.querySelector('#result');
  element.innerHTML=labels.map(item=>`<div>${item}</div>`).join('');

  //设置语音监听
  recognizer.listen(res=>{
    //找出识别最接近的值
    const {scores}=res;
    const maxValue=Math.max(...scores);
    const index=scores.indexOf(maxValue);
    console.log(labels[index]);

    element.innerHTML=labels.map((l,i)=>{
      return  `<div style="background:${i===index && 'green'}">${l}</div>`
    }).join('');
  },{
    //识别频率
    overlapFactor:0.3,
    //有75%以上接近,打印结果
    probabilityThreshold:0.75
  });
});

html部分

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    h3{
      text-align: center;
    }
    #result{
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
    }
    #result>div{
      width: 150px;
      height: 150px;
      line-height: 150px;
      margin-right: 30px;
      text-align: center;
    }
  </style>
</head>
<body>
  <h3>语音识别</h3>
  <div id="result"></div>
</body>
<script src="./t8.js"></script>
</html>

执行结果

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐