feat: add sound supporting

This commit is contained in:
eeeXun 2021-12-23 10:03:12 +08:00
parent b0932c7bbe
commit d849958898
4 changed files with 47 additions and 1 deletions

View File

@ -34,3 +34,5 @@ It use Google Translate's API(free), so it may not work when you send too many r
- Select Language: `Ctrl + S`
- Select other Widget: `TAB`/`Shift+TAB`
- Select: `ENTER`
- Play Sound on left: `CTRL + K`
- Play Sound on right: `CTRL + L`

23
Sound.py Normal file
View File

@ -0,0 +1,23 @@
from urllib.request import urlopen
from urllib.parse import quote
from pygame import mixer
import time
class Sound:
def __init__(self):
self.url = "https://translate.google.com.vn/translate_tts?ie=UTF-8&q={}&tl={}&client=tw-ob"
self.cache_file = "/tmp/translate.mp3"
mixer.init()
def play(self, message, language):
source = urlopen(self.url.format(quote(message), language))
# write to file
with open(self.cache_file, "wb") as fp:
fp.write(source.read())
# play sound
mixer.music.load(self.cache_file)
mixer.music.play()
while mixer.music.get_busy():
time.sleep(0.1)

View File

@ -1,5 +1,6 @@
import npyscreen
import curses
from Sound import Sound
from TUI.Box import EditBox
readme = '''
@ -15,6 +16,8 @@ readme = '''
- ALT + ENTER : Search
- CTRL + D : Delete all input
- CTRL + S : Select Language
- CTRL + K : Play left sound
- CTRL + L : Play right sound
'''
class MainForm(npyscreen.FormBaseNew):
@ -47,6 +50,11 @@ class MainForm(npyscreen.FormBaseNew):
# select language
"^S": self.change_language,
# play sound on the left window
"^K": self.play_left,
# play sound on the right window
"^L": self.play_right,
}
self.add_handlers(event_handlers)
@ -129,7 +137,19 @@ class MainForm(npyscreen.FormBaseNew):
# Though npyscreen's documentation mention that we should avoid using DISPLAY() function
# I can't display Chinese or Japanese,etc correctly when I didn't use this function.
self.DISPLAY()
def play_left(self, event):
if self.input.value != "":
message = self.input.value
language = self.parentApp.translator.fr
Sound().play(message, language)
def play_right(self, event):
if self.output.value != "":
message = self.output.value
language = self.parentApp.translator.to
Sound().play(message, language)
def remove_text(self, event):
self.input.value = ""
self.input.update()

View File

@ -1,3 +1,4 @@
npyscreen==4.10.5
requests==2.25.1
urllib3>=1.26.5
pygame