単語帳データベース

語学レッスン用に音声もデータベース化するようにしました。音声ファイルの作成はgoogle翻訳を使用しています。肝となるのは wget コマンドを使用して音声ファイルのダウンロードを実施したことです。これにより作業時間が大幅に短縮できました。 

#! /bin/bash
ctlfile="insert.txt"
if [ -z ${logfile} ] 
then 
 logfile="/dev/null"
fi
host=127.0.0.1
DB=xxxxxx

# テーブル vocabulary のフィールドは以下のような形式としました。
mysql -h ${host} ${DB}<< _SQL_
 create table if not exists vocabulary (
  id int primary key auto_increment,
  ch text,
  py text,
  ja text,
  voice mediumblob
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
_SQL_

ch=`cat $ctlfile |\
     awk 'NR==1{print $0}'`
py=`cat $ctlfile |\
     awk 'NR==2{print $0}'`
ja=`cat $ctlfile |\
     awk 'NR==3{print $0}'`

# 谷歌翻译から ${ch} の音声データをダウンロードしBASE64エンコードする
# ダウンロードにあたっては http://healingk.blog72.fc2.com/blog-entry-63.html を参考にしました
mp3file="download_voice.mp3"
agent="Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0"
wget --user-agent="${agent}" \
"http://translate.google.com/translate_tts?tl=zh-ch&q="${ch}"&client=tw-ob" \
-O ${mp3file}
voice=`base64 -w0 ${mp3file}`
rm ${mp3file}

# 汉语,拼音,日本語訳,BASE64エンコードした音声をデータベース登録する
mysql -N -h ${host} ${DB} << _SQL_ >> ${logfile}
 insert into vocabulary(ch,py,ja,voice) 
         value("$ch","$py","$ja","$voice");
 select id,ch from vocabulary 
                 where id=LAST_INSERT_ID();
_SQL_
cat << + > insert.txt
欢迎
Huānyíng
いらっしゃい

+
insertDB    

 のようにして使用します。