1851浏览
查看: 1851|回复: 0

【智控万物】乐高EV3播报新闻

[复制链接]
本帖最后由 云天 于 2021-2-27 13:44 编辑

【准备工作】
【智控万物】乐高EV3播报新闻图5

参考:https://mc.dfrobot.com.cn/thread-308419-1-1.html
【项目目的】
【智控万物】乐高EV3播报新闻图4

利用乐高EV3语音播报新闻
【ev3dev中speak方法】
在ev3dev中的sound库中有speak方法,可以进行朗读,但它只能朗读英语。
  1.     def speak(self, text, espeak_opts='-a 200 -s 130', volume=100, play_type=PLAY_WAIT_FOR_COMPLETE):
  2.         """ Speak the given text aloud.
  3.         Uses the ``espeak`` external command.
  4.         :param string text: The text to speak
  5.         :param string espeak_opts: ``espeak`` command options (advanced usage)
  6.         :param int volume: The play volume, in percent of maximum volume
  7.         :param play_type: The behavior of ``speak`` once playback has been initiated
  8.         :type play_type: ``Sound.PLAY_WAIT_FOR_COMPLETE``, ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` or ``Sound.PLAY_LOOP``
  9.         :return: When python3 is used and ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` is specified, returns the
  10.             spawn subprocess from ``subprocess.Popen``; ``None`` otherwise
  11.         """
  12.         self._validate_play_type(play_type)
  13.         self.set_volume(volume)
  14.         cmd = "/usr/bin/espeak --stdout %s '%s' | /usr/bin/aplay -q" % (espeak_opts, text)
  15.         return self._audio_command(cmd, play_type)
复制代码
python程序
  1. from ev3dev2.sound import Sound
  2. sound=Sound()
  3. sound.speak('I Love You',volume=20)
复制代码
换个思路,将文字传给百度AI平台进行语音合成,EV3使用ev3dev中的sound库播放传回来的音频文件。

【清理python2.7】

在乐高EV3的ev3dev中安装有python2.7和python3.7,使用pip安装时,会安装到python2.7中。我要使用python3,而pip3并不存在。通过以下方法,先删除python2.7,再安装python3.7下的pip3.
  1. 1.卸载python2.7sudo apt-get remove python2.7
  2. 2.卸载python2.7及其依赖sudo apt-get remove --auto-remove python2.7
  3. 3.消除python2.7sudo apt-get purge python2.7 or sudo apt-get purge --auto-remove python2.7
  4. 4、安装pip3:
  5. sudo apt install python3-pip
  6. 5、更新pip3。
复制代码


有网友说在Python可以使用用playsound module:playsound module是一个可以跨平台使用的库,不需要其他依赖的库,直接利用pip或者IDE的库管理功能安装就行。
  1. pip install playsound
复制代码

使用此方法在乐高EV3 并不能播放由百度传来的mp3。


【使用sound库】
  1. class Sound(object):
  2.     """
  3.     Support beep, play wav files, or convert text to speech.
  4.     Examples::
  5.         from ev3dev2.sound import Sound
  6.         spkr = Sound()
  7.         # Play 'bark.wav':
  8.         spkr.play_file('test.wav')
  9.         # Introduce yourself:
  10.         spkr.speak('Hello, I am Robot')
  11.         # Play a small song
  12.         spkr.play_song((
  13.             ('D4', 'e3'),
  14.             ('D4', 'e3'),
  15.             ('D4', 'e3'),
  16.             ('G4', 'h'),
  17.             ('D5', 'h')
  18.         ))
复制代码
  1. def play_file(self, wav_file, volume=100, play_type=PLAY_WAIT_FOR_COMPLETE):
  2.         """ Play a sound file (wav format) at a given volume. The EV3 audio subsystem will work best if
  3.         the file is encoded as 16-bit, mono, 22050Hz.
  4.         :param string wav_file: The sound file path
  5.         :param int volume: The play volume, in percent of maximum volume
  6.         :param play_type: The behavior of ``play_file`` once playback has been initiated
  7.         :type play_type: ``Sound.PLAY_WAIT_FOR_COMPLETE``, ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` or ``Sound.PLAY_LOOP``
  8.         :return: When python3 is used and ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` is specified, returns the
  9.             spawn subprocess from ``subprocess.Popen``; ``None`` otherwise
  10.         """
  11.         if not 0 < volume <= 100:
  12.             raise ValueError('invalid volume (%s)' % volume)
  13.         if not wav_file.endswith(".wav"):
  14.             raise ValueError('invalid sound file (%s), only .wav files are supported' % wav_file)
  15.         if not os.path.exists(wav_file):
  16.             raise ValueError("%s does not exist" % wav_file)
  17.         self._validate_play_type(play_type)
  18.         self.set_volume(volume)
  19.         return self._audio_command('/usr/bin/aplay -q "%s"' % wav_file, play_type)
复制代码


在ev3dev中有sound库,但它只能播放wav格式。而百度语音合成之后的是mp3格式。需要将mp3转成wav。
可使用ffmpeg
【安装ffmpeg】
  1. sudo add-apt-repository ppa:kirillshkrogalev/ffmpeg-next
  2. sudo apt-get update
  3. sudo apt-get install ffmpeg
复制代码

例如:
  1. from os import path
  2. from pydub import AudioSegment
  3. #files
  4. src = "1.mp3"
  5. dst = "test.wav"
  6. # convert wav to mp3
  7. sound = AudioSegment.from_mp3(src)
  8. sound.export(dst, format="wav")
复制代码

【百度语音合成】
1、创建应用
【智控万物】乐高EV3播报新闻图1
2、获取相应参数
【智控万物】乐高EV3播报新闻图2
3、安装语音合成 Python SDK
  1. pip3 install baidu-aip
复制代码
[color=rgba(0, 0, 0, 0.85)]AipSpeech是语音合成的Python SDK客户端,为使用语音合成的开发人员提供了一系列的交互方法。
  1. from aip import AipSpeech
  2. """ 你的 APPID AK SK """
  3. APP_ID = '你的 App ID'
  4. API_KEY = '你的 Api Key'
  5. SECRET_KEY = '你的 Secret Key'
  6. client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
复制代码
请求说明
  • 合成文本长度必须小于1024字节,如果本文长度较长,可以采用多次请求的方式。文本长度不可超过限制

[color=rgba(0, 0, 0, 0.85)]举例,要把一段文字合成为语音文件:

  1. result  = client.synthesis('你好百度', 'zh', 1, {
  2.     'vol': 5,
  3. })
  4. # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
  5. if not isinstance(result, dict):
  6.     with open('audio.mp3', 'wb') as f:
  7.         f.write(result)
复制代码

【测试程序】
  1. from aip import AipSpeech
  2. from os import path
  3. from pydub import AudioSegment
  4. from ev3dev2.sound import Sound
  5. """ 你的 APPID AK SK """
  6. APP_ID = '你自己的'
  7. API_KEY = '你自己的'
  8. SECRET_KEY = '你自己的'
  9. client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
  10. result  = client.synthesis('你好百度', 'zh', 1, {
  11.     'vol': 5,
  12. })
  13. # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
  14. if not isinstance(result, dict):
  15.     with open('audio.mp3', 'wb') as f:
  16.         f.write(result)
  17. src = "audio.mp3"
  18. dst = "audio.wav"
  19. # convert wav to mp3
  20. sound = AudioSegment.from_mp3(src)
  21. sound.export(dst, format="wav")
  22. spkr = Sound()
  23. spkr.play_file(dst,volume=20)
复制代码
【爬取新闻标题】
BS4全称是Beatiful Soup,它提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为tiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。
1、安装
  1. pip3 install Beautifulsoup4
复制代码
2、测试程序
  1. from bs4 import BeautifulSoup
  2. import requests
  3. import time
  4. from ev3dev2.display import Display
  5. display=Display()
  6. url = "http://news.baidu.com"
  7. r = requests.get(url)
  8. html = r.text
  9. soup = BeautifulSoup(html, 'html.parser')
  10. li_list = soup.select('.hotnews > ul > li')
  11. for li in li_list:
  12.    a_title = li.a.string
  13.    print(a_title)
  14.    time.sleep(10)
复制代码
【读百度新闻标题】
  1. from aip import AipSpeech
  2. from os import path
  3. from pydub import AudioSegment
  4. from ev3dev2.sound import Sound
  5. from bs4 import BeautifulSoup
  6. import requests
  7. import time
  8. from ev3dev2.display import Display
  9. APP_ID = '23708135'
  10. API_KEY = '3r5tdSmk4mtATr8SzXbWr2Dz'
  11. SECRET_KEY = 'Vgc4DeTAiLnpZ9gGwA86DsKaHyGVedKz'
  12. client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
  13. display=Display()
  14. url = "http://news.baidu.com"
  15. r = requests.get(url)
  16. html = r.text
  17. soup = BeautifulSoup(html, 'html.parser')
  18. li_list = soup.select('.hotnews > ul > li')
  19. for li in li_list:
  20.     a_title = li.a.string
  21.     result  = client.synthesis(a_title, 'zh', 1, {
  22.     'vol': 5,
  23. })
  24.     if not isinstance(result, dict):
  25.        with open('audio.mp3', 'wb') as f:
  26.           f.write(result)
  27.     src = "audio.mp3"
  28.     dst = "audio.wav"
  29.     sound = AudioSegment.from_mp3(src)
  30.     sound.export(dst, format="wav")
  31.     spkr = Sound()
  32.     spkr.play_file(dst,volume=100)
  33.     time.sleep(20)
复制代码

【获取新闻内容】打印测试,只读取第一段。
  1. from bs4 import BeautifulSoup
  2. import requests
  3. import time
  4. # 定义url
  5. url = "https://share.gmw.cn/guancha/2021-02/25/content_34643362.htm"
  6. r = requests.get(url)
  7. r.encoding = 'utf-8'
  8. html = r.text
  9. soup = BeautifulSoup(html, 'html.parser')
  10. # 取出结果div
  11. myAttrs = {'class': 'u-mainText'}
  12. table = soup.find_all(name='div', attrs=myAttrs)
  13. l=table[0]
  14. p=l.find_all('p')
  15. j = 1
  16. for x in p:
  17.     if j != 2:
  18.         pass
  19.     else:
  20.         print(x.text)
  21.     j = j + 1
复制代码

【播报新闻视频】
【智控万物】乐高EV3播报新闻图3



【完整程序】

  1. from aip import AipSpeech
  2. from pydub import AudioSegment
  3. from ev3dev2.display import Display
  4. from ev3dev2.sound import Sound
  5. from os import path
  6. from bs4 import BeautifulSoup
  7. import requests
  8. import time
  9. APP_ID = '23708135'
  10. API_KEY = '3r5tdSmk4mtATr8SzXbWr2Dz'
  11. SECRET_KEY = 'Vgc4DeTAiLnpZ9gGwA86DsKaHyGVedKz'
  12. client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
  13. display = Display()
  14. url = "http://news.baidu.com"
  15. r = requests.get(url)
  16. r.encoding = 'utf-8'
  17. html = r.text
  18. soup = BeautifulSoup(html, 'html.parser')
  19. li_list = soup.select('.hotnews > ul > li')
  20. for li in li_list:
  21.     url = li.a['href']
  22.     r = requests.get(url)
  23.     r.encoding = 'utf-8'
  24.     html = r.text
  25.     soup = BeautifulSoup(html, 'html.parser')
  26.     myAttrs = {'class': 'u-mainText'}
  27.     table = soup.find_all(name='div', attrs=myAttrs)
  28.     if len(table)>0:
  29.        l = table[0]
  30.        p = l.find_all('p')
  31.        j = 1
  32.        for x in p:
  33.         if j == 2:
  34.             # print(x.text)
  35.             result = client.synthesis(x.text, 'zh', 1, {'vol': 5})
  36.             if not isinstance(result, dict):
  37.                 with open('audio.mp3', 'wb') as f:
  38.                     f.write(result)
  39.                     src = "audio.mp3"
  40.                     dst = "audio.wav"
  41.                     sound = AudioSegment.from_mp3(src)
  42.                     sound.export(dst, format="wav")
  43.                     spkr = Sound()
  44.                     spkr.play_file(dst, volume=100)
  45.         else:
  46.             pass
  47.         j = j + 1
复制代码


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail