Skip to content

Commit

Permalink
Move "hear" function to class method
Browse files Browse the repository at this point in the history
  • Loading branch information
guanciottaman committed May 19, 2023
1 parent da13c0f commit 754b9fb
Showing 1 changed file with 24 additions and 21 deletions.
45 changes: 24 additions & 21 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,27 +64,9 @@ def search_word(self):
definitions.insert('end', '\n -------------- \n')
definitions.grid(row=1, column=1, padx=20, pady=20)
definitions.configure(state='disabled')
def hear():
"""Play word phonetics"""
try:
phcs = json[0]['phonetics']
for i in range(len(phcs)):
audio_link = phcs[i]['audio']
if audio_link == '':
continue
break
audio_response = requests.get(audio_link, timeout=10)
with open(f'{json[0]["word"]}.mp3', 'wb') as file_:
file_.write(audio_response.content)
playsound.playsound(f'{Path().cwd() / f"""{json[0]["word"]}.mp3"""}',
block=False)
os.remove(f'{json[0]["word"]}.mp3')
except requests.exceptions.MissingSchema:
showerror('Word has no audio', 'The API did not provide audio for this word.')
except playsound.PlaysoundException:
os.system(f'{"main.exe" if "main.exe" in os.listdir() else "python main.py"}')
sys.exit(0)
hear_btn = CTkButton(self, width=50, height=30, text='Listen', command=hear,

hear_btn = CTkButton(self, width=50, height=30, text='Listen',
command=lambda: self.hear(json),
font=('Segoe UI', 16, 'bold'))
hear_btn.grid(row=0, column=2, pady=20, sticky='e')
show_api_response = CTkButton(self, width=100, height=30, text='Show API response',
Expand All @@ -94,6 +76,27 @@ def hear():
except KeyError:
showerror('Word not found', 'The word was not found correctly. \nPlease try again.')

def hear(self, json):
"""Play word phonetics"""
try:
phcs = json[0]['phonetics']
for i in range(len(phcs)):
audio_link = phcs[i]['audio']
if audio_link == '':
continue
break
audio_response = requests.get(audio_link, timeout=10)
with open(f'{json[0]["word"]}.mp3', 'wb') as file_:
file_.write(audio_response.content)
playsound.playsound(f'{Path().cwd() / f"""{json[0]["word"]}.mp3"""}',
block=False)
os.remove(f'{json[0]["word"]}.mp3')
except requests.exceptions.MissingSchema:
showerror('Word has no audio', 'The API did not provide audio for this word.')
except playsound.PlaysoundException:
os.system(f'{"main.exe" if "main.exe" in os.listdir() else "python main.py"}')
sys.exit(0)


if __name__ == '__main__':
app = App()
Expand Down

0 comments on commit 754b9fb

Please sign in to comment.