ロボットプログラミングⅡ-2021:ROS2演習7-音声合成 (Python)
lecture
2021.11.182021.12.09
この記事は金沢工業大学 ロボティクス学科で2021年後学期開講中のロボットプログラミングⅡ用です.
今回も音声認識と同様にPythonライブラリをROS2化します。使用する音声合成ライブラリはgTTS(Google Text-to-Speech)です。これは、Google Translate text-to-speech APIのインタフェースとなっています。Googleのサービスを使うのでオンラインでのみ使用可能です。詳細は以下の公式サイトをご覧ください。
gTTSのサンプルコード
では、早速、gTTSを使ったサンプルを見てみましょう!
from gtts import gTTS
from subprocess import run, PIPE
tts = gTTS('I am Happy Mini', lang='en')
tts.save('text.mp3')
CMD = 'mpg321 text.mp3'
run(CMD.split(), stdout=PIPE, stderr=PIPE)
インストール
$ sudo apt install sox
$ sudo apt install mpg321
$ pip install gTTS
コードの作成
$ mkdir -p ~/src/gTTS
$ cd ~/src/gTTS
ここで,gtts_example.pyというファイルをgtts_example.pyに作成しなければいけません. そのために好きなエディタnanoやgedit等で上のサンプルコードをコピペしてgtts_example.pyとして~/src/gTTSディレクトリの中に保存してください.なお,nanoの使い方がわからない方はこのリンクを見てください.
実行
$ cd ~/src/gTTS
$ python3 gtts_example.py
“I am Happy Mini”とスピーカーから聞こえてきたら成功です。
なお,WSL2を使っている学生は音が聞こえないと思います.次のリンクの設定が必要になります.WSL2では基本的にデバイスを直接扱えないのでリアルロボットを動かすことはできません.そのため,授業では推奨していません.
ROS2化
import rclpy # ROS2
from rclpy.node import Node # ROS2
from std_msgs.msg import String # ROS2
from gtts import gTTS
from subprocess import run, PIPE
import os
class SpeechSynthesis(Node):
def __init__(self):
super().__init__('speech_synthesis') # ROS2
self.CMD = 'mpg321 text.mp3'
self.recog_sub = self.create_subscription(String, 'recog_text', self.sub_cb, 10) #ROS2
def sub_cb(self, msg): # ROS2 サブスクライバ用のコールバック関数
print("Subscribe text:'{}'".format(msg.data))
tts = gTTS(msg.data)
tts.save('text.mp3') # 音声データをファイルに保存
run(self.CMD.split(), stdout=PIPE, stderr=PIPE) # 発話
os.remove('text.mp3') # ファイルを削除
def main():
rclpy.init() # rclpyの初期化
speech_synthesis = SpeechSynthesis() # ノードの生成
rclpy.spin(speech_synthesis) # ノードの実行
speech_synthesis.destroy_node # ノードの破壊
rclpy.shutdown() # rclpyの終了処理
if __name__ == '__main__':
main()
パッケージの作成
$ ~/colcon_ws/src
$ ros2 pkg create --build-type ament_python --node-name speech_synthesis speech_synthesis
ソースコードの作成
ビルド
$ cd ~/colcon_ws
$ colcon build --symlink-install
実行
1つ目の端末で次のコマンドを実行
$ cd ~/colcon_ws
$ source install/local_setup.bash
$ ros2 run speech_synthesis speech_synthesis
2つ目の端末で次のコマンドを実行
$ ros2 topic pub -1 recog_text std_msgs/String "data: 'I love K I T'"
“I love K I T”と音が聞こえれば成功です!
ハンズオン
次の文章を発話させてみよう。
Stay Hungry. Stay Foolish. It was their farewell message as they signed off. Stay Hungry. Stay Foolish. And I have always wished that for myself. And now, as you graduate to begin anew, I wish that for you.
rostopic pubコマンドを使って”I love K I T”と発話させましたが、これをpythonプログラムで実装しよう。
オウム返しのpythonプログラムを作ろう。あなたの発話を音声認識エンジンで変換して、認識結果をトピック名/tts、メッセージ型std_msgs/Stringでパブリッシュします。次に、その認識結果をコンピュータに発話させるパッケージを作りましょう.
次のリンクはROS1の質問応答システムのサンプルプログラムです.これをROS2用にバージョンアップするプログラムを作り,動作を確認してください.
終わり。お疲れ様!
").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),C.head.appendChild(r[0])},abort:function(){i&&i()}}});var Jt,Kt=[],Zt=/(=)\?(?=&|$)|\?\?/;ce.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Kt.pop()||ce.expando+"_"+jt.guid++;return this[e]=!0,e}}),ce.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Zt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Zt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=v(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Zt,"$1"+r):!1!==e.jsonp&&(e.url+=(At.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||ce.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=ie[r],ie[r]=function(){o=arguments},n.always(function(){void 0===i?ce(ie).removeProp(r):ie[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Kt.push(r)),o&&v(i)&&i(o[0]),o=i=void 0}),"script"}),le.createHTMLDocument=((Jt=C.implementation.createHTMLDocument("").body).innerHTML="
",2===Jt.childNodes.length),ce.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(le.createHTMLDocument?((r=(t=C.implementation.createHTMLDocument("")).createElement("base")).href=C.location.href,t.head.appendChild(r)):t=C),o=!n&&[],(i=w.exec(e))?[t.createElement(i[1])]:(i=Ae([e],t,o),o&&o.length&&ce(o).remove(),ce.merge([],i.childNodes)));var r,i,o},ce.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1
").append(ce.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},ce.expr.pseudos.animated=function(t){return ce.grep(ce.timers,function(e){return t===e.elem}).length},ce.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=ce.css(e,"position"),c=ce(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=ce.css(e,"top"),u=ce.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),v(t)&&(t=t.call(e,n,ce.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},ce.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){ce.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===ce.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===ce.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=ce(e).offset()).top+=ce.css(e,"borderTopWidth",!0),i.left+=ce.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-ce.css(r,"marginTop",!0),left:t.left-i.left-ce.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===ce.css(e,"position"))e=e.offsetParent;return e||J})}}),ce.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;ce.fn[t]=function(e){return M(this,function(e,t,n){var r;if(y(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),ce.each(["top","left"],function(e,n){ce.cssHooks[n]=Ye(le.pixelPosition,function(e,t){if(t)return t=Ge(e,n),_e.test(t)?ce(e).position()[n]+"px":t})}),ce.each({Height:"height",Width:"width"},function(a,s){ce.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){ce.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return M(this,function(e,t,n){var r;return y(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?ce.css(e,t,i):ce.style(e,t,n,i)},s,n?e:void 0,n)}})}),ce.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ce.fn[t]=function(e){return this.on(t,e)}}),ce.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.on("mouseenter",e).on("mouseleave",t||e)}}),ce.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){ce.fn[n]=function(e,t){return 0
タイトルとURLをコピーしました
コメント