2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Chat GPTに音声合成のやりかたを聞いてみた

Last updated at Posted at 2023-05-11

はじめに

 Chat GPTにマルナゲドンシリーズ第2弾です。前回は音声認識に挑戦しました。mp3ファイルの文字起こしを行いました。
https://qiita.com/yukinocoding/items/7cf5fa7363f224a0ce11
 今回は文字起こしで生成されたテキストをもう一度音声に戻してみようと思います。

やったこと

 Chat GPTに「Colabで動作するテキストを読み上げる音声合成プログラムを有料のAPIを用いないで書いて」と丸投げしました。生成したコードをそのまま前回のコードに繋げただけなので、開発時間は15分です。最初はGoogleのSpeech to Textを提案してきましたが、有料APIは使いたくなかったので使わないようにお願いしました。
 mp3ファイルがあれば、Colabにコピペで動作します。

main.ipynb
!pip install pydub
!pip install SpeechRecognition
!pip install gTTS
from google.colab import files
from pydub import AudioSegment
import speech_recognition as sr
import os

def convert_audio_to_wav(input_file, output_file):
    audio = AudioSegment.from_mp3(input_file)
    audio.export(output_file, format="wav")

def transcribe_audio(input_file, output_file):
    r = sr.Recognizer()
    with sr.AudioFile(input_file) as source:
        audio = r.record(source)
        text = r.recognize_google(audio, language="ja-JP")
        with open(output_file, "w", encoding="utf-8") as f:
            f.write(text)

# mp3ファイルのアップロード
uploaded = files.upload()

# アップロードされたファイルのパスを取得
input_file = list(uploaded.keys())[0]
output_file = "/content/output.txt"

# mp3をwavに変換
converted_file = "/content/converted.wav"
convert_audio_to_wav(input_file, converted_file)

# 音声を文字起こししてテキストファイルに保存
transcribe_audio(converted_file, output_file)

# 一時ファイルを削除
os.remove(converted_file)
output_file = "/content/output.txt"

# テキストファイルを読み込んで表示
with open(output_file, "r", encoding="utf-8") as f:
    text = f.read()
    print(text)


from gtts import gTTS
from IPython.display import Audio

def text_to_speech(text, output_file):
    tts = gTTS(text=text, lang='ja')  # 言語を指定することもできます
    tts.save(output_file)
    return Audio(output_file)

output_file = "output.mp3"
audio = text_to_speech(text, output_file)
audio

結果

 自分の声のmp3ファイルを作成して、実行してみました。いつもよく聞くGoogleアシススタントの声で音声が返ってきました。ところどころ間違いはありますが、自分の言ったことそのまま話してもらえるのはロマンがありますね。プロポーズなど普段は直接言えないもどかしい思いを伝えるときに使えそうですね。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?