Python實現語音識別功能


利用django實現百度AI 語音識別、合成 RESTful API Python SDK

官方文檔:https://ai.baidu.com/ai-doc/SPEECH/tk4o0bm3v

1. 我們要創建百度ai的語音技術應用

 

 2. 查看應用的 appid apikey secretkey

 

3. 安裝使用Python SDK有如下方式:

  • 如果已安裝pip,執行pip install baidu-aip即可。
  • 如果已安裝setuptools,執行python setup.py install即可。

4. 上代碼

#views.py
from aip import AipSpeech
import os
from rest_framework.response import Response
from rest_framework.views import APIView
import uuid
from django_test.settings import UPLOAD_ROOT
APP_ID = '你的appid'
API_KEY = '你的apikey'
SECRET_KEY = '你的secretkey'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
class Get_pcmAPI(APIView):
    def post(self,request):
        #獲取到pcm對象
        data_pcm = request.data.get('pcm_audio')
        #利用uuid給文件對象級別名防止重復
        pcm_name = str(uuid.uuid4()) + '.pcm'
        #存儲到靜態目錄下
        upload_ = os.path.join(UPLOAD_ROOT,pcm_name)
        with open(upload_,'wb')as pf:
            #將對象以二進制留寫入目錄 chunks將文件分成快上傳
            for i in data_pcm.chunks():
                pf.write(i)
        #獲取文件的方法
        def get_file_content(filePath):
            with open(filePath, 'rb') as fp:
                return fp.read()
        # 識別本地文件
        res = client.asr(get_file_content(upload_), 'pcm', 16000, {
            'dev_pid': 1536,
        })
        print(res) 
        #{'corpus_no': '6845169661962051650', 'err_msg': 'success.', 'err_no': 0, 'result': ['今天天氣怎么樣'], 'sn': '124218514521593765257'}
        return Response({'code':200,'message':res.get('result')[0]})

5. 送上前端小代碼

 利用 js小插件 `js-audio-recorder`

 npm方式:npm i js-audio-recorder 

 官方文檔:https://www.npmjs.com/package/js-audio-recorder

<template>
  <div>
    <Button @click="start_luyin">開始錄音</Button>
    <Button @click="end_luyin">結束錄音</Button>
    <p v-if="messge_audio">
      你剛剛說的話是: {{messge_audio}}
    </p>
  </div>
</template>
<script>
  import Recorder from 'js-audio-recorder';

  var recorder = new Recorder({
    sampleBits: 16,                 // 采樣位數,支持 8 或 16,默認是16
    sampleRate: 16000,              // 采樣率,支持 11025、16000、22050、24000、44100、48000,根據瀏覽器默認值,我的chrome是48000
    numChannels: 1,                 // 聲道,支持 1 或 2, 默認是1
    // compiling: false,(0.x版本中生效,1.x增加中)  // 是否邊錄邊轉換,默認是false
  });
  export default {
    data() {
      return {
        messge_audio: '',
      }
    },
    //定義組建標簽
    components: {},
    filters: {},
    //自定義方法
    methods: {
      start_luyin: function () {
        recorder.start().then(() => {
          alert('開始錄音')
        })
      },
      end_luyin: function () {
        recorder.stop()
        var pcm_auido = recorder.getPCMBlob()
        console.log(pcm_auido)
        var fromdata = new FormData()
        fromdata.append('pcm_audio', pcm_auido)
        this.axios({
          url: 'http://127.0.0.1:8000/getpcm/',
          method: 'post',
          data: fromdata
        }).then((res) => {
          this.messge_audio = res.data.message
        })
      }
    },
    //鈎子方法
    mounted: function () {
      console.log('這是初始化方法');


    },
    //監聽屬性
    watch: {},
    //計算屬性
    computed: {}


  }


</script>

<style>

</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM