AttributeError: 'str' object has no attribute 'raw_data' (Python Voice Assistant) - python-3.x

Hello guys ı am trying to do desktop voice assistant for ubuntu.In my program ıt was working with
os.system("mpg123 audio.mp3")
How can ı use pydub module instead of this line?
but ı don't want to use system to play audio file for talk with me.I think it's slower. I want faster program and today ı was trying pydub module.
There is my program;
from gtts import gTTS
import speech_recognition as sr
import os
import webbrowser
import datetime
import time
import sys
import random
from pydub import AudioSegment
from pydub.playback import play
#sound = AudioSegment.from_mp3('hello.mp3')
#play(sound)
def talkToMe(audio):
print(audio)
tts = gTTS(text=audio, lang= "en")
tts.save("audio.mp3")
play("audio.mp3") #os.system("mpg123 audio.mp3")
def OurCommands():
r = sr.Recognizer()
with sr.Microphone() as source:
os("clear")
print("Ready for next command")
r.pause_threshold = 1
r.adjust_for_ambient_noise(source, duration = 1)
audio = r.listen(source)
try:
command = r.recognize_google(audio)
print("You said: " + command + "\n")
except sr.UnknownValueError:
print("Your last command not understand")
command = str(input("Command: "))
return command
#if statements..
def asistan(command):
if "open web browser" in command:
talkToMe("İt\'s opening")
webbrowser.open("www.google.com.tr")
elif "play music" in command:
mixer.init()
mixer.music.load('/path/to/music/')
mixer.music.play()
elif "stop music" in command:
mixer.music.stop()
elif "thank you" in command:
talkToMe("You're welcome")
elif "shutdown my computer" in command:
talkToMe("I will close after five second")
time.sleep(5)
os.system("shutdown now -h")
elif "open youtube" in command:
webbrowser.open("youtube.com")
hour = int(datetime.datetime.now().hour)
if hour >= 1 and hour <12:
talkToMe("Goodmorning")
elif hour >= 12 and hour < 16:
talkToMe("Good afternoon")
else:
talkToMe("Good night")
while True:
asistan(OurCommands())
but when ı want to use pydub module ı get an error like this;
AttributeError: 'str' object has no attribute 'raw_data'
I tried in my computer this module working for me and played mp3 files.
So now how can ı use pydub module in my program for computer to talk with me.
I think ı need audiosegment but how can ı use in my program do ı have to use another module?
or also ı can work with pydub module in my program? Thanks in advance:)

From the docs:
from pydub import AudioSegment
from pydub.playback import play
sound = AudioSegment.from_file("mysound.wav", format="wav")
play(sound)
Play doesn't expect a filename, it expects input like this. You want
sound = AudioSegment.from_file("audio.mp3", format="mp3")
play(sound)

Related

Speech recognition- microphone not working with exe files made using pyinstaller

import pyttsx3
import speech_recognition as sr
from tkinter import *
from PIL import Image,ImageTk
from customtkinter import *
def micro():
global statement
r=sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source=source)
audio=r.listen(source)
r.energy_threshold=200
r.pause_threshold=0.5
try:
statement=r.recognize_google(audio)
except Exception as e:
statement=" "
engine.say("Pardon me ,please say that again")
engine.runAndWait()
def text_fill():
micro()
text_area.insert("end"," "+ statement)
def main():
global root,label,frame1,engine,image1
root=CTk()
root.geometry("700x600")
root.resizable(0,0)
root.title("Notepad")
frame1=CTkFrame(root,width=150,height=580)
frame1.pack_propagate(False)
frame1.place(x=10,y=10)
set_appearance_mode("dark")
set_default_color_theme("green")
engine=pyttsx3.init()
label=CTkLabel(root,text="File",width=520,height=40,font=("Algerian",30))
label.place(x=170,y=10)
global S
global text_area
text_area=CTkTextbox(root,height=580,width=520,)
text_area.place(x=170,y=60)
image1=CTkImage(Image.open("microphone.png"),size=(26,26))
micro_button=CTkButton(root,image=image1,width=10,height=10,text="",command=text_fill)
micro_button.place(x=650,y=15)
root.update()
root.mainloop()
if __name__=="__main__":
main()
I have converted this program into a .exe file using pyinstaller.
Whenever I run the normal program, i got to see a microphone in the taskbar and the program is running smoothly but when I run its exe file no microphone is shown in the taskbar and thus I am unable to provide input using voice.

Python import pygame does not play an audio

the code just print the name of the song and dont stop after he finish
my code:
import glob
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
songs = glob.glob("C:\\Users\zivsi\Music\\*.mp3")
import random
song = random.choice(songs)
song_name = song.replace("C:\\Users\zivsi\Music\\", "").replace(".mp3", "")
print("song: ", song_name)
pygame.init()
pygame.mixer.music.load(song)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
I did not use from pygame import *
because it cannot be done in def
Use pygame.mixer.music.stop() when you want to stop the music. The pygame.time.Clock().tick(10) computes the time since it was last called and stalls the program until 1/framerate (in your case framerate=10) seconds have passed. Therefore, your code will run until the song is done playing. If instead you want to pause the program for a set amount of time and stop the music from playing, use time.sleep(), which takes seconds as an argument. Possible example:
import glob
import os
import time
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
songs = glob.glob("C:\\Users\zivsi\Music\\*.mp3")
import random
song = random.choice(songs)
song_name = song.replace("C:\\Users\zivsi\Music\\", "").replace(".mp3", "")
print("song: ", song_name)
pygame.init()
pygame.mixer.music.load(song)
pygame.mixer.music.play()
time.sleep(10) #sleep for 10 seconds before moving on
pygame.mixer.music.stop()
thank you. i understand now. my mistake was:
pygame.init() -
i need
pygame.mixer.init()

Why is my code not reaching the While Loop to register my Voice Assistant Wakeword?

I'm creating a Voice Assistant using Python. I'm using pyttsx3 for Text-to-Speech and I have a wakeword set up to activate the Voice Assistant. I'm using the Voice Assistant to do things such as read my calendar and such in a While Loop. But suddenly, the wakeword stops working. What is stopping my code from reaching the While Loop and the rest of the code?
Here is some of the code for my project:
from __future__ import print_function
import subprocess
import pytz
import speech_recognition as sr
import pyttsx3
import time
import os
import datetime
import pickle
import os.path
def speak(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
print("Exception: " + str(e))
return said.lower()
WAKE = "Jarvis"
print("Jarvis is ready")
while True:
print("Jarvis is listening...")
text = get_audio()
if text.count(WAKE) > 0:
speak("Hello Sir, what would you like?")
text = get_audio()
DONE = ["never mind", "goodbye", "I'm done now"]
for phrase in DONE:
if phrase in text:
speak("Alright sir. Goodbye!")
quit()
NOTE_STRS = ["make a note", "write this down", "remember this"]
for phrase in NOTE_STRS:
if phrase in text:
speak("Sure. What would you like me to write down?")
note_text = get_audio()
note(note_text)
speak("Done Sir. I've made a note of that.")
TIME = ["time"]
for phrase in TIME:
if phrase in text:
import datetime
now = datetime.datetime.now()
speak("The current time is %d hours %d minutes" % (now.hour, now.minute))
Please tell me if any code is missing and I can send it to help solve the problem!
HyperionBlaze - What is happening with authenticate_google(). Is there any exception on that call?

How do I stop argparser from printing default search?

Link to my code: https://pastebin.com/y4zLD2Dp
The imports that have not been used are going to be used as I progress through my project, I just like to have all imports I need ready to go. The goal for this program will be a youtube video downloader into mp3 format first. This is my first big project to my standards, only been coding for just over 2 months.
from bs4 import BeautifulSoup
from selenium import webdriver
import requests
import sqlite3
import argparse
import sys
from selenium import webdriver
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
#To get a developer key visit https://console.developers.google.com.
DEVELOPER_KEY = ""
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
'''Searches for results on youtube and stores them in the database.'''
def yt_search(options):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
search = youtube.search().list(q=options.q, part="id,snippet",
maxResults=options.max_results).execute()
video_id = []
#Add results to a list and print them.
for result in search.get("items", []):
if result["id"]["kind"] == "youtube#video":
video_id.append("%s (%s)" % (result["snippet"]["title"],
result["id"]["videoId"]))
else:
continue
print("Videos:\n", "\n".join(video_id), "\n")
def download(args):
print(args)
"""Arguments for the program."""
if __name__ == '__main__':
parser = argparse.ArgumentParser(description= "This program searches for
Youtube links and allows you to download songs from said list. " +
"Please remember to be specific in your
searches for best results.")
parser.add_argument("--q", help="Search term", default="Aeryes")
parser.add_argument("--max-results", help="Max results", default=25)
parser.add_argument("--d", type=download, help="Download a video from
search results.")
args = parser.parse_args()
if len(sys.argv) < 2:
parser.parse_args(['--help'])
sys.exit(1)
try:
yt_search(args)
except HttpError:
print("HTTP error")
The problem that I am having is that upon running the --d cmd in the CLI it works and prints the arg as expected (This is just a test to see that functions are working with the parser) but after it prints a list of default youtube links from --q default which I do not want it to do. How do I stop this from happening. Should I use subparser or is there something that I am missing?
If anyone has good resources for argparser module other than official doc support please share.

(PYTHON) How to play audio file again after executing some code with pygame (pyglet or something similar)?

import time, os, sys, pygame
def some_function():
if < condition >:
time.sleep(5)
pygame.mixer.init()
alert = pygame.mixer.Sound('/home/me/alert.wav')
alert.play()
else:
< something >
some_function()
time.sleep(10)
Now here is a problem.
And I tried different combinations with pygame and pyglet.
pyglet.app.run() works but the rest of the script doesn't run!
pygame.mixer.init()
alert = pygame.mixer.Sound('/home/me/alert.wav')
alert.play()

Resources