|
| 1 | +from io import BytesIO |
| 2 | +import requests |
| 3 | +import bs4 |
| 4 | +from pygame import mixer |
| 5 | +# Import functions from the local package |
| 6 | +from auto_news_reader.voice_to_text import voice_to_text |
| 7 | +from auto_news_reader.mySpeaker import print_say |
| 8 | + |
| 9 | + |
| 10 | +def news_brief(): |
| 11 | + # Locate the website for the NPR news brief |
| 12 | + url = 'https://www.npr.org/podcasts/500005/npr-news-now' |
| 13 | + # Convert the source code to a soup string |
| 14 | + response = requests.get(url) |
| 15 | + soup = bs4.BeautifulSoup(response.text, 'html.parser') |
| 16 | + # Locate the tag that contains the mp3 files |
| 17 | + casts = soup.findAll('a', {'class': 'audio-module-listen'}) |
| 18 | + # Obtain the web link for the mp3 file |
| 19 | + cast = casts[0]['href'] |
| 20 | + # Remove the unwanted components in the link |
| 21 | + mp3 = cast.find("?") |
| 22 | + mymp3 = cast[0:mp3] |
| 23 | + # Play the mp3 using the pygame module |
| 24 | + mymp3 = requests.get(mymp3) |
| 25 | + voice = BytesIO() |
| 26 | + voice.write(mymp3.content) |
| 27 | + voice.seek(0) |
| 28 | + mixer.init() |
| 29 | + mixer.music.load(voice) |
| 30 | + mixer.music.play() |
| 31 | + |
| 32 | + |
| 33 | +while True: |
| 34 | + print_say('Python is listening…') |
| 35 | + inp = voice_to_text().lower() |
| 36 | + print_say(f'you just said: {inp}') |
| 37 | + if inp == "stop listening": |
| 38 | + print_say('Goodbye!') |
| 39 | + break |
| 40 | + # If "news" in your voice command, play news brief |
| 41 | + elif "news" in inp: |
| 42 | + news_brief() |
| 43 | + print_say("Playing the latest News now!") |
| 44 | + # Python listens in the background |
| 45 | + while True: |
| 46 | + background = voice_to_text().lower() |
| 47 | + # Stops playing if you say "stop playing" |
| 48 | + if "stop playing" in background: |
| 49 | + print_say("Stopping the news.") |
| 50 | + mixer.music.stop() |
| 51 | + break |
| 52 | + continue |
0 commit comments