樹莓派小愛同學、天貓精靈、智能音箱、百度語音極速版、百度語音標準版、語音識別、語音合成終極方案

首先需要調用這個方法安裝百度的語音識別

https://ai.baidu.com/ai-doc/SPEECH/Bk4o0bmt3

安裝使用Python SDK有如下方式

  • 如果已安裝pip,執行pip install baidu-aip即可。
  • 如果已安裝setuptools,執行python setup.py install即可。
  • 然後下面的按我的來,然後就可以了

需要更改的地方是最上面的那一排排路徑,還有就是需要自己在百度註冊appId, apiKey , secretKey,如下圖所示:

註冊地址,我好早之前註冊的,所以註冊我就細說不了

https://console.bce.baidu.com/ai/?fromai=1#/ai/speech/overview/index

這個下面是百度官方的tts語音合成 

https://github.com/Baidu-AIP/speech-demo/tree/master/rest-api-tts/python 

這個是我的語音合成,也是老版本百度的語音合成,這個簡潔幹練,沒啥區別的,只是沒有獲取token這一部,但是好像沒啥影響,不過據說token只有一個月的有效期,過了要繼續獲取,最下面代碼中是實時獲取的,不用擔心,我的這個簡短精悍的好像不需要token,哪裏失效一說呢

# 發音人選擇, 基礎音庫:0爲度小美,1爲度小宇,3爲度逍遙,4爲度丫丫,
# 精品音庫:5爲度小嬌,103爲度米朵,106爲度博文,110爲度小童,111爲度小萌,默認爲度小美 
PER = 4
# 語速,取值0-15,默認爲5中語速
SPD = 5
# 音調,取值0-15,默認爲5中語調
PIT = 5
# 音量,取值0-9,默認爲5中音量
VOL = 5
# 下載的文件格式, 3:mp3(default) 4: pcm-16k 5: pcm-8k 6. wav
AUE = 3

robotVoicePath = '/home/pi/share/tts/dvic/voice.mp3'

# 將本地文件進行語音合成,這個和下面那個tts都可以用,用這個方便快捷
def tts(word):
    result  = client.synthesis(word,'zh',1, {
        'vol':VOL,'per':PER,'spd':SPD,'pit':PIT
    })

# 合成正確返回audio.mp3,錯誤則返回dict
    if not isinstance(result, dict):
        with open(robotVoicePath, 'wb') as f:
            f.write(result)
        f.close()
        print 'tts successful'


#其中robotVoicePath 自己設定, 還有tts 後面那個括號中的word,例如: tts("你傻不傻")
#然後VOL、PER、SPD、PIT自己設定一下

下面是官方的語音識別代碼demo,極速版本的代碼這以下鏈接中註釋了一部分,大家注意了

 https://github.com/Baidu-AIP/speech-demo/blob/master/rest-api-asr/python/asr_raw.py

下面是我的百度語音識別普通版和極速版,需要更改一些路徑,還有自己的appId, apiKey , secretKey,需要改了才能跑,具體demo看最下面一個代碼,那最全。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
from aip import AipSpeech
import sys
import pyaudio
import wave
import requests
import json
import os, re
import time
import base64
import random

IS_PY3 = sys.version_info.major == 3
if IS_PY3:
    from urllib.request import urlopen
    from urllib.request import Request
    from urllib.error import URLError
    from urllib.parse import urlencode
    from urllib.parse import quote_plus
    timer = time.perf_counter
else:
    import urllib2
    from urllib import quote_plus
    from urllib2 import urlopen
    from urllib2 import Request
    from urllib2 import URLError
    from urllib import urlencode
    timer = time.time


voicePath = '/home/pi/share/tts/dvic/voice.pcm'
textPath = '/home/pi/share/tts/dtext/text.txt'
robotVoicePath = '/home/pi/share/tts/dvic/voice.mp3'
shaoyePath = '/home/pi/share/shaoye/kele'
novoicePath = '/home/pi/share/novoice/kele'

''' 你的APPID AK SK  參數在申請的百度雲語音服務的控制檯查看'''
APP_ID = 'XXXXXXXXXXXX'
API_KEY = 'XXXXXXXXXXXXXXXXXXXXXX'
SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

# 下載的文件格式, 3:mp3(default) 4: pcm-16k 5: pcm-8k 6. wav
AUE = 3

FORMATS = {3: "mp3", 4: "pcm", 5: "pcm", 6: "wav"}
FORMAT = FORMATS[AUE]
CUID = "123456XXXXXXXXXXXXXXXXXxxxxx"
TTS_URL = 'http://tsn.baidu.com/text2audio'
TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'
SCOPE_TTS = 'audio_tts_post'  # 有此scope表示有tts能力,沒有請在網頁裏勾選
# 需要識別的文件
AUDIO_FILE = 'test.pcm'  # 只支持 pcm/wav/amr 格式,極速版額外支持m4a 格式
# 文件格式
FORMAT = AUDIO_FILE[-3:]  # 文件後綴只支持 pcm/wav/amr 格式,極速版額外支持m4a 格式
DEV_PID = 80001
ASR_URL = 'http://vop.baidu.com/pro_api'
SCOPE_STT = 'brain_enhanced_asr'  # 有此scope表示有極速版能力,沒有請在網頁裏開通極速版


# 讀取文件
def get_file_content(filePath):  # filePath  待讀取文件名
    with open(filePath, 'rb') as fp:
        return fp.read()

def stt_normal(filename):  # 語音識別標準版
    wordStr = ''
    # 識別本地文件
    result = client.asr(get_file_content(filename),
                        'pcm',
                        16000,
                        {'dev_pid': 1537, }  # dev_pid參數表示識別的語言類型 1536表示普通話
                        )
    print result

    # 解析返回值,打印語音識別的結果
    if result['err_msg'] == 'success.':
        print "stt successful"
        word = result['result'][0].encode('utf-8')  # utf-8編碼
        if word != '':
            if word[len(word) - 3:len(word)] == ',':
                print word[0:len(word) - 3]
                with open(textPath, 'w') as f:
                    f.write(word[0:len(word) - 3])
                f.close()
            else:
                print(word.decode('utf-8').encode('utf-8'))
                wordStr = word.decode('utf-8').encode('utf-8')
                with open(textPath, 'w') as f:
                    f.write(word)
                f.close()
        else:
            print
            "音頻文件不存在或格式錯誤"
    else:
        print
        "錯誤"
    return wordStr

#####################  以下是極速版,建議用這個,快就對了  #####################

class DemoError(Exception):
    pass

"""  TOKEN start """

def getBaiduToken():   #百度語音識別極速版
    print("fetch token begin")
    params = {'grant_type': 'client_credentials',
              'client_id': API_KEY,
              'client_secret': SECRET_KEY}
    post_data = urlencode(params)
    if (IS_PY3):
        post_data = post_data.encode('utf-8')
    req = Request(TOKEN_URL, post_data)
    try:
        f = urlopen(req, timeout=5)
        result_str = f.read()
    except URLError as err:
        print('token http response http code : ' + str(err.code))
        result_str = err.read()
    if (IS_PY3):
        result_str = result_str.decode()

    print(result_str)
    result = json.loads(result_str)
    print(result)
    if ('access_token' in result.keys() and 'scope' in result.keys()):
        if not SCOPE_TTS in result['scope'].split(' '):
            raise DemoError('scope is not correct')
        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))
        return result['access_token']
    else:
        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')

"""  TOKEN end """


def stt(filename):
    token = getBaiduToken()

    speech_data = []
    with open(filename, 'rb') as speech_file:
        speech_data = speech_file.read()

    length = len(speech_data)
    if length == 0:
        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)
    speech = base64.b64encode(speech_data)
    if (IS_PY3):
        speech = str(speech, 'utf-8')
    params = {'dev_pid': DEV_PID,
             #"lm_id" : LM_ID,    #測試自訓練平臺開啓此項
              'format': FORMAT,
              'rate': RATE,
              'token': token,
              'cuid': CUID,
              'channel': 1,
              'speech': speech,
              'len': length
              }
    post_data = json.dumps(params, sort_keys=False)
    # print post_data
    req = Request(ASR_URL, post_data.encode('utf-8'))
    req.add_header('Content-Type', 'application/json')
    try:
        begin = timer()
        f = urlopen(req)
        result_str = f.read()
        print ("Request time cost %f" % (timer() - begin))
    except URLError as err:
        print('asr http response http code : ' + str(err.code))
        result_str = err.read()

    if (IS_PY3):
        result_str = str(result_str, 'utf-8')
    print(result_str)

    wordStr = ''
    # 解析返回值,打印語音識別的結果
    print(result_str)
    result = json.loads(result_str)
    # 解析返回值,打印語音識別的結果
    if result['err_msg'] == 'success.':
        print "stt successful"
        word = result['result'][0].encode('utf-8')  # utf-8編碼
        if word != '':
            if word[len(word) - 3:len(word)] == ',':
                print word[0:len(word) - 3]
                with open(textPath, 'w') as f:
                    f.write(word[0:len(word) - 3])
                f.close()
            else:
                print(word.decode('utf-8').encode('utf-8'))
                wordStr = word.decode('utf-8').encode('utf-8')
                with open(textPath, 'w') as f:
                    f.write(word)
                f.close()
        else:
            print
            "音頻文件不存在或格式錯誤"
    else:
        print
        "錯誤"
    return wordStr

這個下面是我集成好了的代碼,大家可以拿去用,需要更改一下路徑什麼的,還有自己的appId, apiKey , secretKey

#!/usr/bin/python
# -*- coding: UTF-8 -*-
#import snowboydetect  這裏是語音喚醒需要的代碼
from aip import AipSpeech
#import tuling   圖靈機器人,現在要錢了
import sys
import pyaudio
import wave
import requests
import json
import os, re
import time
import base64
import random

IS_PY3 = sys.version_info.major == 3
if IS_PY3:
    from urllib.request import urlopen
    from urllib.request import Request
    from urllib.error import URLError
    from urllib.parse import urlencode
    from urllib.parse import quote_plus
    timer = time.perf_counter
else:
    import urllib2
    from urllib import quote_plus
    from urllib2 import urlopen
    from urllib2 import Request
    from urllib2 import URLError
    from urllib import urlencode
    timer = time.time

reload(sys)
sys.setdefaultencoding('utf-8')

voicePath = '/home/pi/share/tts/dvic/voice.pcm'
textPath = '/home/pi/share/tts/dtext/text.txt'
robotVoicePath = '/home/pi/share/tts/dvic/voice.mp3'
shaoyePath = '/home/pi/share/shaoye/kele'
novoicePath = '/home/pi/share/novoice/kele'

''' 你的APPID AK SK  參數在申請的百度雲語音服務的控制檯查看'''
APP_ID = 'XXXXXXXXXXXX'
API_KEY = 'XXXXXXXXXXXXXXXXXXXXXX'
SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

# 發音人選擇, 基礎音庫:0爲度小美,1爲度小宇,3爲度逍遙,4爲度丫丫,
# 精品音庫:5爲度小嬌,103爲度米朵,106爲度博文,110爲度小童,111爲度小萌,默認爲度小美 
PER = 4
# 語速,取值0-15,默認爲5中語速
SPD = 5
# 音調,取值0-15,默認爲5中語調
PIT = 5
# 音量,取值0-9,默認爲5中音量
VOL = 5
# 下載的文件格式, 3:mp3(default) 4: pcm-16k 5: pcm-8k 6. wav
AUE = 3

FORMATS = {3: "mp3", 4: "pcm", 5: "pcm", 6: "wav"}
FORMAT = FORMATS[AUE]
CUID = "123456XXXXXXXXXXXXXXXXXxxxxx"
TTS_URL = 'http://tsn.baidu.com/text2audio'
TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'
SCOPE_TTS = 'audio_tts_post'  # 有此scope表示有tts能力,沒有請在網頁裏勾選
# 需要識別的文件
AUDIO_FILE = 'test.pcm'  # 只支持 pcm/wav/amr 格式,極速版額外支持m4a 格式
# 文件格式
FORMAT = AUDIO_FILE[-3:]  # 文件後綴只支持 pcm/wav/amr 格式,極速版額外支持m4a 格式
DEV_PID = 80001
ASR_URL = 'http://vop.baidu.com/pro_api'
SCOPE_STT = 'brain_enhanced_asr'  # 有此scope表示有極速版能力,沒有請在網頁裏開通極速版

# 採樣率
RATE = 16000  # 固定值

# 新建一個AipSpeech
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

#執行shell錄音功能
def shellRecord_old(time):
    os.system('arecord -D "plughw:1,0" -d ' + str(time)  + ' -r 16000  -t wav -f S16_LE ' + voicePath)

#新版本錄音功能,可錄製pcm
def shellRecord(time):
    CHUNK = 512
    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    RATE = 16000
    RECORD_SECONDS = time
    WAVE_OUTPUT_FILENAME = voicePath

    p = pyaudio.PyAudio()

    stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

    print("recording...")

    frames = []

    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)

    print("done")

    stream.stop_stream()
    stream.close()
    p.terminate()

    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()

#播放語音
def mplayerSYMp3():
    os.system('mplayer ' + shaoyePath + str(random.randint(1,10)) + '.mp3 > /dev/null 2>&1 &')

#播放語音
def mplayerNOMp3():
    os.system('mplayer ' + novoicePath + str(random.randint(1,10)) + '.mp3 > /dev/null 2>&1 &')

#播放語音
def mplayerMp3():
    os.system('mplayer ' + robotVoicePath + ' > /dev/null 2>&1 &')

#打開攝像頭
def openCamera():
    os.system('sh /usr/local/mjpg/camera.sh > /dev/null 2>&1 &')

#關閉攝像頭
def closeCamera():
    os.system("ps -ef | grep mjpg | grep -v grep | awk '{print $2}' | xargs kill -9")

#播放音樂
def mplayerMusic(fileName):
    os.system('mplayer ' + '/home/pi/share/music/'+ '*' + fileName  + '*' + ' > /dev/null 2>&1 &')

def closeMplayer():
    os.system("ps -ef | grep mplayer | grep -v grep | awk '{print $2}' | xargs kill -9")

def compareStr(s1, s2):
    return difflib.SequenceMatcher(None, s1, s2).quick_ratio()

# 讀取文件
def get_file_content(filePath):  # filePath  待讀取文件名
    with open(filePath, 'rb') as fp:
        return fp.read()

#語音識別普通版本
def stt_normal(filename):  # 語音識別
    wordStr = ''
    # 識別本地文件
    result = client.asr(get_file_content(filename),
                        'pcm',
                        16000,
                        {'dev_pid': 1537, }  # dev_pid參數表示識別的語言類型 1536表示普通話
                        )
    print result

    # 解析返回值,打印語音識別的結果
    if result['err_msg'] == 'success.':
        print "stt successful"
        word = result['result'][0].encode('utf-8')  # utf-8編碼
        if word != '':
            if word[len(word) - 3:len(word)] == ',':
                print word[0:len(word) - 3]
                with open(textPath, 'w') as f:
                    f.write(word[0:len(word) - 3])
                f.close()
            else:
                print(word.decode('utf-8').encode('utf-8'))
                wordStr = word.decode('utf-8').encode('utf-8')
                with open(textPath, 'w') as f:
                    f.write(word)
                f.close()
        else:
            print
            "音頻文件不存在或格式錯誤"
    else:
        print
        "錯誤"
    return wordStr

# 讀取文件
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

# 將本地文件進行語音合成,這個和下面那個tts都可以用,用這個方便快捷
def tts(word):
    result  = client.synthesis(word,'zh',1, {
        'vol':VOL,'per':PER,'spd':SPD,'pit':PIT
    })

# 合成正確返回audio.mp3,錯誤則返回dict
    if not isinstance(result, dict):
        with open(robotVoicePath, 'wb') as f:
            f.write(result)
        f.close()
        print 'tts successful'

################################################## 最新版本百度極速語音識別和語音合成 ########################################
class DemoError(Exception):
    pass

"""  TOKEN start """

def getBaiduToken():   #百度語音識別極速版token
    print("fetch token begin")
    params = {'grant_type': 'client_credentials',
              'client_id': API_KEY,
              'client_secret': SECRET_KEY}
    post_data = urlencode(params)
    if (IS_PY3):
        post_data = post_data.encode('utf-8')
    req = Request(TOKEN_URL, post_data)
    try:
        f = urlopen(req, timeout=5)
        result_str = f.read()
    except URLError as err:
        print('token http response http code : ' + str(err.code))
        result_str = err.read()
    if (IS_PY3):
        result_str = result_str.decode()

    print(result_str)
    result = json.loads(result_str)
    print(result)
    if ('access_token' in result.keys() and 'scope' in result.keys()):
        if not SCOPE_TTS in result['scope'].split(' '):
            raise DemoError('scope is not correct')
        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))
        return result['access_token']
    else:
        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')

"""  TOKEN end """

def tts_new(word):
    token = getBaiduToken()
    tex = quote_plus(word)  # 此處TEXT需要兩次urlencode
    print(tex)
    params = {'tok': token, 'tex': tex, 'per': PER, 'spd': SPD, 'pit': PIT, 'vol': VOL, 'aue': AUE, 'cuid': CUID,
              'lan': 'zh', 'ctp': 1}  # lan ctp 固定參數

    data = urlencode(params)
    print('test on Web Browser' + TTS_URL + '?' + data)

    req = Request(TTS_URL, data.encode('utf-8'))
    has_error = False
    try:
        f = urlopen(req)
        result_str = f.read()

        headers = dict((name.lower(), value) for name, value in f.headers.items())

        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)
    except  URLError as err:
        print('asr http response http code : ' + str(err.code))
        result_str = err.read()
        has_error = True

    #save_file = "error.txt" if has_error else 'result.' + FORMAT
    save_file = "error.txt" if has_error else robotVoicePath
    with open(save_file, 'wb') as of:
        of.write(result_str)

    if has_error:
        if (IS_PY3):
            result_str = str(result_str, 'utf-8')
        print("tts api  error:" + result_str)

    print("result saved as :" + save_file)

def stt(filename):
    token = getBaiduToken()

    speech_data = []
    with open(filename, 'rb') as speech_file:
        speech_data = speech_file.read()

    length = len(speech_data)
    if length == 0:
        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)
    speech = base64.b64encode(speech_data)
    if (IS_PY3):
        speech = str(speech, 'utf-8')
    params = {'dev_pid': DEV_PID,
             #"lm_id" : LM_ID,    #測試自訓練平臺開啓此項
              'format': FORMAT,
              'rate': RATE,
              'token': token,
              'cuid': CUID,
              'channel': 1,
              'speech': speech,
              'len': length
              }
    post_data = json.dumps(params, sort_keys=False)
    # print post_data
    req = Request(ASR_URL, post_data.encode('utf-8'))
    req.add_header('Content-Type', 'application/json')
    try:
        begin = timer()
        f = urlopen(req)
        result_str = f.read()
        print ("Request time cost %f" % (timer() - begin))
    except URLError as err:
        print('asr http response http code : ' + str(err.code))
        result_str = err.read()

    if (IS_PY3):
        result_str = str(result_str, 'utf-8')
    print(result_str)

    wordStr = ''
    # 解析返回值,打印語音識別的結果
    print(result_str)
    result = json.loads(result_str)
    # 解析返回值,打印語音識別的結果
    if result['err_msg'] == 'success.':
        print "stt successful"
        word = result['result'][0].encode('utf-8')  # utf-8編碼
        if word != '':
            if word[len(word) - 3:len(word)] == ',':
                print word[0:len(word) - 3]
                with open(textPath, 'w') as f:
                    f.write(word[0:len(word) - 3])
                f.close()
            else:
                print(word.decode('utf-8').encode('utf-8'))
                wordStr = word.decode('utf-8').encode('utf-8')
                with open(textPath, 'w') as f:
                    f.write(word)
                f.close()
        else:
            print
            "音頻文件不存在或格式錯誤"
    else:
        print
        "錯誤"
    return wordStr

############################################################# 最新版本百度語音極速識別和語音合成 ###################################

def getWeatherTemp():
    url = 'http://wthrcdn.etouch.cn/weather_mini?city=武漢'
    response = requests.get(url)
    wearher_json = json.loads(response.text)
    weather_dict = wearher_json['data']
    str = '%s%s%s%s' % (
    '親愛的少爺',
    '當前溫度', weather_dict['wendu'],'℃')
    return str

def getWeather():
    url = 'http://wthrcdn.etouch.cn/weather_mini?city=武漢'
    response = requests.get(url)
    wearher_json = json.loads(response.text)
    weather_dict = wearher_json['data']
    str = '%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s' % (
    '親愛的少爺',
    '今天是', weather_dict['forecast'][0]['date'], ',', '\n',
    '天氣', weather_dict["forecast"][0]['type'], ',', '\n',
    weather_dict['city'], '最', weather_dict['forecast'][0]['low'], ',', '\n',
    '最', weather_dict['forecast'][0]['high'], ',', '\n',
    '當前溫度', weather_dict['wendu'], '℃', ',', '\n',
    weather_dict["forecast"][0]['fengxiang'],
    weather_dict["forecast"][0]['fengli'].split("[CDATA[")[1].split("]")[0])
    return str

def getTWeather():
    url = 'http://wthrcdn.etouch.cn/weather_mini?city=武漢'
    response = requests.get(url)
    wearher_json = json.loads(response.text)
    weather_dict = wearher_json['data']
    str = '%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s' % (
    '親愛的少爺',
    '明天是', weather_dict['forecast'][1]['date'], ',', '\n',
    '天氣', weather_dict["forecast"][1]['type'], ',', '\n',
    weather_dict['city'], '最', weather_dict['forecast'][1]['low'], ',', '\n',
    '最', weather_dict['forecast'][1]['high'], ',', '\n',
    weather_dict["forecast"][1]['fengxiang'],
    weather_dict["forecast"][1]['fengli'].split("[CDATA[")[1].split("]")[0],
    '。', '\n')
    return str

# Return CPU temperature as a character string
def getCPUtemperature():
    res = os.popen('vcgencmd measure_temp').readline()
    return(res.replace("temp=","").replace("'C\n",""))

# Return % of CPU used by user as a character string
def getCPUuse():
    return(str(os.popen("top -bn1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))

# Return RAM information (unit=kb) in a list
# Index 0: total RAM
# Index 1: used RAM
# Index 2: free RAM
# Index 3: perc RAM
def getRAMinfo():
    p = os.popen('free')
    i = 0
    while 1:
        i = i + 1
        line = p.readline()
        if i==2:
            return(line.split()[1:6])

#基本的業務邏輯
def loopRecord():
    textStr = ''
    #播放已經保存好的喚醒語音
    mplayerSYMp3()
    #需要兩秒鐘播放完畢
    time.sleep(2)
    #開始錄音,錄音3秒鐘,可以自定義時間
    shellRecord(3)
    #開始語音識別
    textStr = stt(voicePath)
    print textStr
    if '明' in textStr and '天' in textStr and '氣' in textStr:
        #語音合成
        tts(getTWeather())
        mplayerMp3()
        time.sleep(13)
    elif '今' in textStr and '天' in textStr and '氣' in textStr:
        tts(getWeather())
        mplayerMp3()
        time.sleep(15)
    elif 'cpu' in textStr or 'CPU' in textStr:
        # CPU informatiom
        CPU_temp = getCPUtemperature()
        CPU_usage = getCPUuse()
        tts('CPU溫度' + str(CPU_temp) + '度' + ',' + 'CPU使用率百分之' + str(CPU_usage))
        mplayerMp3()
        time.sleep(7)
    elif '溫度' in textStr:
        tts(getWeatherTemp())
        mplayerMp3()
        time.sleep(5)
    elif '內存' in textStr:
        # Output is in kb, here I convert it in Mb for readability
        RAM_stats = getRAMinfo()
        RAM_perc = round(100 * float(RAM_stats[1]) / float(RAM_stats[0]), 2)
        RAM_realPerc = round(100 * (float(RAM_stats[1]) + float(RAM_stats[4])) / float(RAM_stats[0]), 2)
        tts('內存已使用百分之' + str(RAM_perc) + ',' + '實際已使用百分之' + str(RAM_realPerc))
        mplayerMp3()
        time.sleep(8)
    elif '打開' in textStr and '攝像' in textStr:
	openCamera()
        tts('攝像頭已打開')
        mplayerMp3()
        time.sleep(2)       
    elif '關閉' in textStr and '攝像' in textStr:
	closeCamera()
        tts('攝像頭已關閉')
        mplayerMp3()
        time.sleep(2)
    elif '隨便' in textStr or '隨機' in textStr or '放首歌' in textStr or '播放音樂' in textStr:
        fileNameList = os.listdir('/home/pi/share/music')
        fileName = fileNameList[random.randint(0,len(fileNameList) - 1)]
        mplayerMusic(fileName)
    elif '換一首' in textStr or '下一首' in textStr or '下一曲' in textStr:
        closeMplayer()
        time.sleep(2)
        fileNameList = os.listdir('/home/pi/share/music')
        fileName = fileNameList[random.randint(0,len(fileNameList) - 1)]
        mplayerMusic(fileName)    
    elif '停止' in textStr or '不要' in textStr or '休息' in textStr or '關閉音樂' in textStr or '安靜' in textStr:
        closeMplayer()
    elif '防守' in textStr or '放手' in textStr or '放首' in textStr or '播放' in textStr or '放一首' in textStr or '唱一首' in textStr or '聽一下' in textStr or '聽一首' in textStr:
	newStr = textStr.replace('播放','').replace('放一首','').replace('唱一首','').replace('聽一下','').replace('聽一首','').replace('放首','').replace('放手','').replace('防守','')
	newStr = textStr.replace('播放','').replace('放一首','').replace('唱一首','').replace('聽一下','').replace('聽一首','').replace('放首','').replace('放手','').replace('防守','')
        closeMplayer()
        mplayerMusic(newStr)
    else:
        mplayerNOMp3()
        time.sleep(2)
        

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章