分享

树莓派 python 百度语音控制 gpio 控制开关灯 | | URl

 啊司com 2017-08-03


20140926150759750

1、安装

Python2安装GPIO库需要输入命令:

Python
1
2
sudo apt-get install python-dev
sudo apt-get install python-rpi.gpio

Python3安装GPIO库需要输入命令:

Python
1
2
sudo apt-get install python-dev
sudo apt-get install python3-rpi.gpio

2 测试gpio

建立一个测试文件,test.py

然后运行之:  sudo python test.py

注意:首先要sudo 要有管理员权限才能控制io口.其次你的连线得注意一下,下面gpio.high是代表11口输出高电平,大概不到3.3的电压,而且电流也比较小,一般而言是用作继电器或者放大电路中的信号元.

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
# -*- coding: utf-8 -*-    
import RPi.GPIO as GPIO    
import time    
# BOARD编号方式,基于插座引脚编号    
GPIO.setmode(GPIO.BOARD)    
# 输出模式    
GPIO.setup(11, GPIO.OUT)    
    
while True:    
    GPIO.output(11, GPIO.HIGH)    
    time.sleep(1)    
    GPIO.output(11, GPIO.LOW)    
    time.sleep(1)

如果你能出现灯光闪烁,那么就算是成功拉,

 

 

3.语音部分

主要部分请参照这文章,还有之前有很多可以

然后在其中加入判断就可以了

注意”开门后面的逗号要中文编码下的逗号”

Python
1
2
3
if(cmp(duihua,'开门,')==0):
    print "识别开门"
    GPIO.output(11, GPIO.LOW)

Python
1
2
3
if(cmp(duihua,'关门,')==0):
    print "识别关门"
    GPIO.output(11, GPIO.HIGH)

注意在开头要加上下面的申明.

Python
1
2
3
4
5
6
7
# -*- coding: utf-8 -*-    
import RPi.GPIO as GPIO    
import time    
# BOARD编号方式,基于插座引脚编号    
GPIO.setmode(GPIO.BOARD)    
# 输出模式    
GPIO.setup(11, GPIO.OUT)

 

4.树莓派下源代码

说明:环境挺麻烦,请看前面给出的链接,然后需要将建立文件夹:yuyinduihua 放在/home/pi 下,因为下面有使用绝对路径的地方,.需要调整.

有可能出错的地方是百度语音的token需要自己粘帖上去..这个有点懒的改了.

.就是在这里后面tok的一串数字是他的识别码,过一段时间就会更换,失效,所以需要自己输出token函数的内容,然后再粘帖过去,,希望还是需要多学习一下之前几篇关于百度语音的才能控制自如.

Python
1
url = "http://tsn.baidu.com/text2audio?tex="+dic_json['text']+"&lan=zh&per=0&pit=1&spd=7&cuid=7519663&ctp=1&tok=24.ece6cfa6b5821f481deceef114da892e.2592000.1467287744.282335-7519663"

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# -*- coding: utf-8 -*-
#from pyaudio import PyAudio, paInt16
import numpy as np
from datetime import datetime
import wave
import time
import urllib, urllib2, pycurl
import base64
import json
import os
import sys
import RPi.GPIO as GPIO
import time
# BOARD编号方式,基于插座引脚编号
GPIO.setmode(GPIO.BOARD)
# 输出模式
GPIO.setup(11, GPIO.OUT)
reload(sys)
sys.setdefaultencoding( "utf-8" )
save_count = 0
save_buffer = []
t = 0
sum = 0
time_flag = 0
flag_num = 0
filename = '2.wav'
duihua = '1'
def getHtml(url):
    page = urllib.urlopen(url)
    html = page.read()
    return html
def get_token():
    apiKey = "Ll0c53MSac6GBOtpg22ZSGAU"
    secretKey = "44c8af396038a24e34936227d4a19dc2"
    auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + apiKey + "&client_secret=" + secretKey;
    res = urllib2.urlopen(auth_url)
    json_data = res.read()
    return json.loads(json_data)['access_token']
def dump_res(buf):
    global duihua
    print "字符串类型"
    print (buf)
    a = eval(buf)
    print type(a)
    if a['err_msg']=='success.':
        #print a['result'][0]#终于搞定了,在这里可以输出,返回的语句
        duihua = a['result'][0]
        print duihua
def use_cloud(token):
    fp = wave.open(filename, 'rb')
    nf = fp.getnframes()
    f_len = nf * 2
    audio_data = fp.readframes(nf)
    cuid = "7519663" #产品id
    srv_url = 'http://vop.baidu.com/server_api' + '?cuid=' + cuid + '&token=' + token
    http_header = [
        'Content-Type: audio/pcm; rate=8000',
        'Content-Length: %d' % f_len
    ]
    c = pycurl.Curl()
    c.setopt(pycurl.URL, str(srv_url)) #curl doesn't support unicode
    #c.setopt(c.RETURNTRANSFER, 1)
    c.setopt(c.HTTPHEADER, http_header)   #must be list, not dict
    c.setopt(c.POST, 1)
    c.setopt(c.CONNECTTIMEOUT, 30)
    c.setopt(c.TIMEOUT, 30)
    c.setopt(c.WRITEFUNCTION, dump_res)
    c.setopt(c.POSTFIELDS, audio_data)
    c.setopt(c.POSTFIELDSIZE, f_len)
    c.perform() #pycurl.perform() has no return val
# 将data中的数据保存到名为filename的WAV文件中
def save_wave_file(filename, data):
    wf = wave.open(filename, 'wb')
    wf.setnchannels(1)
    wf.setsampwidth(2)
    wf.setframerate(SAMPLING_RATE)
    wf.writeframes("".join(data))
    wf.close()
NUM_SAMPLES = 2000      # pyAudio内部缓存的块的大小
SAMPLING_RATE = 8000    # 取样频率
LEVEL = 1500            # 声音保存的阈值
COUNT_NUM = 20          # NUM_SAMPLES个取样之内出现COUNT_NUM个大于LEVEL的取样则记录声音
SAVE_LENGTH = 8         # 声音记录的最小长度:SAVE_LENGTH * NUM_SAMPLES 个取样
token = get_token()
key = '05ba411481c8cfa61b91124ef7389767'
api = 'http://www./openapi/api?key=' + key + '&info='
while(True):
    print "kaishi"
    os.system('arecord -D "plughw:1,0" -f S16_LE -d 3 -r 8000 /home/pi/yuyinduihua/2.wav')
    use_cloud(token)
    print "输入内容"
    print duihua
    ############
    #语音识别进行开门的设置#
    ############
    if(cmp(duihua,'开门,')==0):
         print "识别开门"
         GPIO.output(11, GPIO.LOW)
    info = duihua
    duihua = ""
    request = api + info
    response = getHtml(request)
    dic_json = json.loads(response)
    #print '机器人: '.decode('utf-8') + dic_json['text']
    #huida = ' '.decode('utf-8') + dic_json['text']
    a = dic_json['text']
    print type(a)
    unicodestring = a
    # 将Unicode转化为普通Python字符串:"encode"
    utf8string = unicodestring.encode("utf-8")
    print type(utf8string)
    print str(a)
    url = "http://tsn.baidu.com/text2audio?tex="+dic_json['text']+"&lan=zh&per=0&pit=1&spd=7&cuid=7519663&ctp=1&tok=24.ece6cfa6b5821f481deceef114da892e.2592000.1467287744.282335-7519663"
    os.system('mpg123 "%s"'%(url))
    print "wait..1s"
    time.sleep(1)

 

 


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多