can't play mp3 files continuously inside a loop using pygame? [duplicate] - python

This question already has an answer here:
I've got an error when trying to create sound using pygame
(1 answer)
Closed 2 years ago.
Hi i want to play a mp3 but when the function recalled that is logCreater an error shows can load mp3.
First time it play audio correctly but when it's recalled then it cant load mp3.
error msg say's pygame.mixer.music.load cant load xxxxx.mp3 file
Actually this is lil project and this is just one module of it.
Please suggest me the code correction.
Error message is :
Traceback (most recent call last):
File "e:\Tutorials etc\ProjBack\Healthy_programmer_cli\MainModule.py", line 151, in
timCount()
File "e:\Tutorials etc\ProjBack\Healthy_programmer_cli\MainModule.py", line 65, in timCount
EyeExcercise.logCreater()
File "e:\Tutorials etc\ProjBack\Healthy_programmer_cli\EyeExcercise.py", line 45, in logCreater
pygame.mixer.music.load("Eyesound.mp3")
pygame.error: Couldn't open 'Eyesound.mp3'
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
from os.path import expanduser
import time as t
import getpass
usernm = getpass.getuser()
from datetime import datetime
import pygame
def userDirFinder():
from os.path import expanduser
usrpth = expanduser("~")
mainp = os.path.join(usrpth, "Documents")
return mainp
def checknSetdir():
mainp=userDirFinder()
target_path = os.path.join(mainp,"HealthManger","Eye_Excercise_log")
if os.path.exists(target_path):
os.chdir(target_path)
else:
os.makedirs(target_path)
os.chdir(target_path)
def getCurrentDateandTime():
Dat = datetime.now()
currentD = Dat.strftime("%d/%m/%Y")
currentT = Dat.strftime("%I:%M %p")
return currentD , currentT
def logCreater():
print("Countdown paused")
pygame.mixer.init()
pygame.mixer.music.load("Eyesound.mp3")
pygame.mixer.music.play(-1)
write_msg = f"Eye Excercise Done by {usernm}"
while 1:
try:
print("Time for a Eye Excercise Break , After the Eye Excercise")
usr_msg = input("Type \"Done\" to stop this alarm: ")
usr_msg = usr_msg.lower()
if usr_msg != "done":
raise ValueError("Invalid Answer")
elif "done" == usr_msg:
checknSetdir()
with open("eye_excercise_log.txt","a") as fi:
cdat , ctim = getCurrentDateandTime()
fi.write(f"Date: {cdat} Time: {ctim} Message: {write_msg}\n")
# print("Log Created")
pygame.mixer.music.stop()
break
except Exception as e:
print(e)
def logReader():
try:
checknSetdir()
with open("eye_excercise_log.txt","r") as fi:
lis = fi.readlines()
for i in lis:
print(i)
input("Press to contiue")
except FileNotFoundError:
print("File is not created Yet")
input("Press to contiue")
if __name__ =="__main__":
while True:
logCreater()

First time it play audio correctly but when it's recalled then it cant load mp3
After playing the music, the current working directory is changed in the function checknSetdir, by os.chdir(target_path).
Get the current working directory at the begin of the application:
import os
currentWorkDir = os.getcwd()
Use an absolut path to load the file "Eyesound.mp3":
pygame.mixer.music.load(os.path.join(currentWorkDir, "Eyesound.mp3"))

Related

Pyinstaller output exe not working but works fine in command prompt

i got a script by name students.py
the code is this
import time
import keyboard as kb
import random
import numpy as np
while True:
Students = ["Nishesh","Anshika","Naincy","Geeta","Rajneesh"]
exitcon = ["close","exit","Quit","quit","Exit","Close"]
maxrn = len(Students)
Marks = [100,2,100,100,100]
uinnput = input("Enter Roll no of students : ")
if uinnput in exitcon:
break
if uinnput.isdigit():
if uinnput > "0" and uinnput < "6":
rn = int(uinnput) - 1
print(Students[rn]," : " , Marks[rn])
else:
print("Please enter a number between 1 and ",maxrn)
else:
print("Please enter a number between 1 and ",maxrn)
its a pretty simple script and I converted it to exe but with pyinstallerand when i run the exe it gives this error
Traceback (most recent call last): File "students.py", line 10, in <module> RuntimeError: input(): lost sys.stdin
it works fine in when running the python file with cmd but this exe isn't

pygame: Unable to forward songs with .wav extension

When I try to forward a song with .wav extension in pygame , I get an error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\default\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1884, in __call__
return self.func(*args)
File "C:\Users\default\PycharmProjects\pythonProject1\main.py", line 14, in forward
pygame.mixer.music.play(start = forwarded_pos)
pygame.error: Position not implemented for music type
Here's the code:
from tkinter import *
import pygame
root = Tk()
pygame.init()
def play():
pygame.mixer.music.load("test.wav")
pygame.mixer.music.play()
def forward():
forwarded_pos = pygame.mixer.music.get_pos() + 10
pygame.mixer.music.load("test.wav")
pygame.mixer.music.play(start = forwarded_pos)
play_button = Button(root , text = "Play song" , command = play)
play_button.grid(row = 0 , column = 0)
forward_button = Button(root , text = "Forward song" , command = forward)
forward_button.grid(row = 1 , column = 0 , pady = 10)
mainloop()
As I was continuously getting that error , I tried this:
def forward():
forwarded_pos = pygame.mixer.music.get_pos() + 10
pygame.mixer.music.set_pos(forwarded_pos)
But when I did that, I keep getting another error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\default\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1884, in __call__
return self.func(*args)
File "C:\Users\default\PycharmProjects\pythonProject1\main.py", line 13, in forward
pygame.mixer.music.set_pos(forwarded_pos)
pygame.error: set_pos unsupported for this codec
Is there any way to fix this problem?
I think forwarding is not supported in .wav format , so fixing this problem with any other format(except .mp3) will also be ok.
Get_pos and set_pos are triggering the same errors for me. You actually don't need them as you can assign the forwarded_pos when you start playing the music as follows. This doesn't seem to work for .wav but it does for .ogg and .mp3 formats.
import pygame
from os import path
pygame.init()
pygame.mixer.init()
snd_dir = path.join(path.dirname(__file__), "snd")
song = path.join(snd_dir, 'song_name.ogg')
forwarded_pos = 22
mixer = pygame.mixer.music
mixer.load(song)
mixer.play(-1, forwarded_pos)
# doesn't work for wav sounds types
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)

'Job' object has no attribute 'Wednesday' error when scheduling event

I tried to make it as easy as possible to understand, I have no backgound in IT, I am doing this auto login program to join my own classes. Can anyone tell me why its not working?
The error is this :
"Traceback (most recent call last):
File "/home/omiceyo/PycharmProjects/datetimepractice/main.py", line 79, in <module>
Wednesday()
File "/home/omiceyo/PycharmProjects/datetimepractice/main.py", line 56, in Wednesday
schedule.every().Wednesday.at(Class).do(join_meeting(666666666))
AttributeError: 'Job' object has no attribute 'Wednesday' "
Here is my code:
import datetime
import schedule
import subprocess
import pyautogui
import time
#Define join meeting
def join_meeting(meetingid):
# open Tencent Meeting windows 10
subprocess.call(["C:\Program Files (x86)\Tencent\WeMeet\wemeetapp.exe"])
# 5 secs wait for lag
time.sleep(5)
# Click join button
join_button = pyautogui.locateCenterOnScreen('Tencent_meeting_join_button.png')
pyautogui.moveTo(join_button)
pyautogui.click()
# Putting in the Meeting ID
Id_button = pyautogui.locateCenterOnScreen('Tencent_meeting_id.png')
pyautogui.moveTo(Id_button)
pyautogui.click()
pyautogui.write(meetingid)
# Disable mic
mic_button = pyautogui.locateCenterOnScreen('mic_button.png')
pyautogui.moveTo(mic_button)
pyautogui.click()
# time.sleep(4)
# Joining the meeting
Meeting_button = pyautogui.locateCenterOnScreen('Join_meeting.png')
pyautogui.moveTo(Meeting_button)
pyautogui.click()
time.sleep(4)
pyautogui.press('enter')
#Class times
Class = "10:00"
Class2= "14:00"
Class3= "16:00"
Class4= "19:00"
Test= "18:25"
#Define weekdays
def Monday():
schedule.every().Monday.at(Class2).do(join_meeting(6666666))
def Tuesday():
schedule.every().Tuesday.at(Class3).do(join_meeting(6666666))
def Wednesday():
schedule.every().Wednesday.at(Class).do(join_meeting(666666666))
schedule.every().Wednesday.at(Class2).do(join_meeting(66666666))
schedule.every().Wednesday.at(Test).do(join_meeting(6666666666))
def Thursday():
schedule.every().Thursday.at(Class4).do(join_meeting(666666666))
def Friday():
schedule.every().Friday.at(Class4).do(join_meeting(66666666))
def Saturday():
print("Its saturday")
Date = datetime.datetime.now()
Today = (Date.strftime("%a"))
if Today=="Mon":
Monday()
elif Today=="Tue":
Tuesday()
elif Today=="Wed":
Wednesday()
elif Today=="Thu":
Thursday()
elif Today=="Fri":
Friday()
elif Today=="Sat":
Saturday()
else:
print("Today is sunday")
while True:
schedule.run_pending()
time.sleep(60)
Check the capitalization for the days of the week per their documentation.
wednesday will get called now but will run into a type error associated with join_meeting(meetingID):
TypeError: the first argument must be callable
A quick resolution to the TypeError is to not pass the meetingid through the scheduler and define it else where, example:
schedule.every().wednesday.at(Class2).do(join_meeting)
Also, the while loop is indented too far and won't run.

Facing issue while providing dynamic name to file in python through a function

the line : with open('new%s.txt' % intg ,'a') as g : is giving error in below code.
Every time I call the function "Repeat", it should create file with name new1.txt, new2.txt and so on.
But it is giving error : "name 'intg' is not defined"
I want dynamic name for screenshot file and txt file, to prevent overwriting of file.
The code is for selecting data from a software, copying it, and pasting it in new file each time.
Please help:
import win32api
import win32com.client
import pyautogui
import pyperclip
shell = win32com.client.Dispatch("WScript.Shell")
win32api.Sleep(5000)
def repeat( intg ):
import pyautogui
pyautogui.moveTo(17, 213)
win32api.Sleep(2000)
pyautogui.screenshot('%s.png' % intg)
pyautogui.click()
win32api.Sleep(2000)
pyautogui.hotkey('ctrl', 'c')
s = pyperclip.paste()
win32api.Sleep(2000)
with open('new%s.txt' % intg ,'a') as g:
g.write(s)
print("done")
repeat( intg = 1 )
repeat( intg = 2 )
win32api.Sleep(5000)
print ("done")
you can concatenate integer and strings doing so:
with open('new' + str(intg) + '.txt','a') as g:
or doing so:
with open('new{0}.txt'.format(intg),'a') as g:

Python AttributeError: module 'runAnalytics' has no attribute 'run'

I am trying to grab an input from my main.py file using tkinter and then use that input in runAnalytics.py
main.py
import runAnalytics
import tkinter
import os
import centerWindow
loadApplication = tkinter.Tk()
loadApplication.title("Stock Analytics")
loadApplication.geometry("1080x720")
label1 = tkinter.Label(loadApplication, text = "Ticker")
input1 = tkinter.Entry(loadApplication)
loadAnalytics = tkinter.Button(loadApplication, text = "Load Analytics", command = runAnalytics.run)
centerWindow.center(loadApplication)
loadAnalytics.pack()
label1.pack()
input1.pack()
loadApplication.mainloop()
runAnalytics.py
from yahoo_finance import Share
from main import input1
import tkinter
import os
import centerWindow
def run():
ticker = input1
loadAnalytics = tkinter.Tk()
loadAnalytics.title("$" + ticker + " Data")
loadAnalytics.geometry("1080x720")
print ("Price per share: " + ticker.get_price())
ticker.refresh()
print ("Price per share: " + ticker.get_price())
print("The dividend yield is: " + ticker.get_dividend_yield())
print("The 52 week low is: " + ticker.get_year_low())
print("The 52 week high is: " + ticker.get_year_high())
print("The volume is: " + ticker.get_volume())
print("The previous close was: " + ticker.get_prev_close())
print("The previous open was: " + ticker.get_open())
loadAnalytics.mainloop()
My error message reads as follows;
Traceback (most recent call last):
File "C:\Users\MyName\Documents\Python Projects\MarketData\main.py", line 1, in <module>
import runAnalytics
File "C:\Users\MyName\Documents\Python Projects\MarketData\runAnalytics.py", line 2, in <module>
from main import input1
File "C:\Users\MyName\Documents\Python Projects\MarketData\main.py", line 13, in <module>
loadAnalytics = tkinter.Button(loadApplication, text = "Load Analytics", command = runAnalytics.run)
AttributeError: module 'runAnalytics' has no attribute 'run'
You have a circular import:
import runAnalytics
# ..
from main import input1
By the time main is being imported again, runAnalytics has not yet had a chance to execute the def run():.. section.
Resolve this by removing the from main import input1 line, and pass that object in as an argument instead:
def run(input1):
passing this in from the main.py module when you call the function:
loadAnalytics = tkinter.Button(loadApplication, text = "Load Analytics", command = lambda: runAnalytics.run(input1))
Apart from the circular import, there is also the issue that whatever file you run as the main script in Python will be stored as the __main__ module. Importing that same script again will lead to a second module being created, now under the name main, and any objects created in that module are distinct from those in __main__.
Next, you'll want to remove the loadAnalytics.mainloop() call from run as you should not start a new mainloop from an already running loop. You probably also want to create a new TopLevel window instead of creating another Tk() root. You'd have to pass in loadApplication to run too if you go this way.
from runAnalytics import run
loadAnalytics = tkinter.Button(loadApplication, text="Load Analytics", command=run)
You don't want to start another mainloop of tk. Instead you should pass the root and create a toplevel window.
def run(root):
ticker = input1
parent = Toplevel(root)
parent.title("$" + ticker + " Data")
# the rest of your code
Try adding () to the end of runAnalytics.run. You are currently telling it to look for a run attribute which it doesn't have instead of a function
loadAnalytics = tkinter.Button(loadApplication, text = "Load Analytics", command = runAnalytics.run())

Categories

Resources