I'm using the code:
import pygame, sys, datetime
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640, 480))
screen.fill((0, 0, 0, 255))
pygame.display.set_caption("TESTIFICATE")
if datetime.date.today().month == 12 and datetime.date.today().day == 25:
pygame.mixer.music.load("8bit-jingle-twist.mp3")
print("Merry Christmas!")
else:
pygame.mixer.music.load("timeless-mountains.mp3")
print("Loading Music...")
pygame.mixer.music.play(-1, 0.0)
print("Playing Background Music...")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Both 8bit-jingle-twist.mp3 and timeless-mountains.mp3 exist and can be played by VLC. My volume is on, as is my confusion.
Are you sure you are looking for them in the correct directory?
Try specifying the full path, ie
"c:/programs/mygame/music/8bit-jingle-twist.mp3"
Very strange, I simply copied your code and just changed the audio files to ones I had, and it worked perfectly fine.
I think therefore it has something to do with the files themselves.
It could be as Hugh Bothwell pointed out, the file path. In which case you could do three things:
Use the whole file path:
pygame.mixer.music.load("C:/blah/blah/blah/8bit-jingle-twist.mp3")
Use no file path (The file must then be in the same folder as the program)
pygame.mixer.music.load("8bit-jingle-twist.mp3")
Or use a one folder jump, where you have a folder inside the same folder as your program.
So for example you have your program in "My Documents", then you make another folder called "Music for Pygame" inside of "My Documents". Then the code would be:
pygame.mixer.music.load("Music for Pygame/8bit-jingle-twist.mp3")
I mostly use the last option, so that you can keep your files organized by having a folder for music, a folder for images, etc. and the program would still work if you moved the folder it was in.
Of course it could also be the audio file itself. Make sure it really is a .mp3 and that it plays fine (VLC is too awesome and can play anything, try playing it on Windows media or something just in case)
Also if using Windows 7 OS, try running it as an administrator and it might fix the problem.
(I ran the code on Windows XP and it worked fine just now)
NEW ANSWER:
if you saved your mp3 file as 'filename.mp3', and you wrote down the .mp3 file extension yourself, then the filename in pygame's pygame.mixer.music.load() function must be written as 'filename.mp3.mp3', because python expects you to add the .mp3. Sometimes the .mp3 is already included in the filename if you manually saved it as that.
Therefore, try this:
pygame.mixer.music.load('filename.mp3.mp3')
Related
Trying to design and call open a basic customized pygame window that pops up right after the program starts. The window I'm producing gets minimized by default instead of just opening. It's also not updating the color, and it immediately crashes when I open the tab that it's in.
# I'm running Windows 10 with Spyder (Python 3.9), if that matters
# This is the entire code:
import pygame
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Shooter Friends (Version 1.0)")
# Color presets
WHITE = (255,255,255)
BLACK = (0,0,0)
# Event loop
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
WIN.fill(WHITE)
pygame.display.update()
pygame.quit()
# Ensure the game only executes in the file named: space_shooter.py
if __name__ == "__space_shooter__":
main()
For context, I'm a beginner level student just trying to generate a basic white display for now, with dimensions: 9ooW x 500H, and centered ideally so that the pygame window's center is superimposed onto the center of my computer screen. I want this window to pop up as soon as the program starts running, and it should stay open for an indefinite amount of time, or until exited from with the X icon.
It seems to be producing the window right away as intended, but it places it into a minimized tab instead of an opened window display for some reason. The window pops open if I click on the tab, but it's filled in with black regardless of what values I insert into WIN.fill(R,B,G) as arguments. Also, the program immediately becomes non-responsive with the message: (Not responding) next to the game's title (at the top of the pygame window, not in the Spyder terminal).
Seems like it's not able to update for some reason, possibly causing it to crash, but I'm not really sure. I'm not getting any runtime or syntax errors from Python, but I do get a "Python is not responding" message from Windows in the pygame window as well as whenever I try to close the window using the X icon. Any help is much appreciated!
The problem is in the following line:
if __name__ == "__space_shooter__":
The __name__ variable will not contain the file name of the current script. If the script is ran directly, it will contain "__main__". If the script is imported by another script, it will contain the file name of that other script.
In order to check the script's file name, which you according to the comment wanted to do, you have to use the __file__ variable. The only problem is that the __file__ variable does not only containt the file name, but also the file path and the file extension. That's why I would use the str.endswith function, which checks whether a certain string ends with a given string. There are also some more complicate and reliable ways, but I will leave it to this:
if __file__.endswith("space_shooter.py"):
However, it is more common to check whether the current file is being ran directly instead of being imported from another file. This allows other files to import and use the functions and classes present in the file, without that everything in the file is ran too.
For this, you have to use the __name__ variable:
if __name__ == "__main__":
As said above, the __name__ variable will contain "__main__" when the file is ran directly. Thus we can compare __name__ with it to know whether the file is ran directly or not.
For more information on the __name__ variable, there is more explanation and a useful example.
I'm not able to add in images to my programme in Pycharm, I've imported Pygame and os and it wouldn't work. The image is in .png format 64 bit from flaticon.com
Is there something else I need to do to be able to add it in, I was following a PyGame tutorial online since I'm a beginner in programming
The python launcher just glitches when I add anything to do with an image. everything else works perfectly fine.
Here is the entire code of the project so far:
import pygame
import os
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Space Invaders - GAME ONE (PyGame)")
playerImg = pygame.image.load('space-invaders.png')
playerX = 370
playerY = 480
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0))
pygame.display.update()
this is the error message:
playerImg = pygame.image.load('space-invaders.png')
pygame.error: Couldn't open space-invaders.png
Process finished with exit code 1
it just glitches with any addition of an image. If I remove all image related code, it works fine
Also, import os just greys out in the editor
First check if the image is in the same folder as your .py. Next, make sure the image is really .png not just renamed for example, check this by trying to load another image. Last but not the least, check the spelling, maybe the name of the picture is misspelled. Since you are not using paths I can't remember anything else that could cause the issue.
Also, I do not know if it is the mistake during the copy process but last 2 lines of code need to be inside the for loop. And why you have imported os?
EDIT: Answer to the OP question in the comment
By importing os you can now use this module, nothing more. Here is how you can locate your .png file:
current_dir = os.path.dirname(__file__) #The location of your `.py`
img_dir = os.path.join(current_dir, "img_dir") #Path to the folder where your `png` is
player_img = pygame.image.load(os.path.join(img_dir, "space-invaders.png"))
Instead of "img_dir" you need to put the name of your folder, or the path, depending on the folder location.
I have a problem I'm working in Pycharm with Pygames and when I try to pygame.image.load() it doesn't work and keep telling me that it cannot find 'load' in image.py. I redownloaded the pygame package and it still doesn't work. Please help me.
Pycharm reports: Cannot find reference 'load' in 'image.py', when using pygame.image.load(). The code breaks when trying to execute this command.
import pygame
pygame.init()
surface = pygame.display.set_mode((1200, 720))
my_image = pygame.image.load('maxresdefault.bmp')
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
surface.fill((188, 22, 22)
surface.blit(my_image, (0, 0))
pygame.display.update()
pygame.quit()
After redownloading the Pygame package, the issue persists.
Code
Error text
PyCharm seems to have problems referencing load but it works fine. There are 2 separate issues here: The load error (which can be ignored as there doesn't seem to be any way around it, and PyGame works just fine), but secondly, and more importantly, there is a problem with your image file itself. Is it in the same directory as your script? .bmp is the standard format so that shouldn't be an issue. If it's in the right directory, and the name is correct, try converting it to a .png or .jpg image.
I'm trying to write a small bit of code to play music files in the background of a game. The problem I'm coming across is that despite all the code being laid out and phrased properly no sound files will play. I put several print statements in the code and it seems to suggest that the sound file is either not loading or is simply not playing once it loads?
import pygame
def musicPlayer():
print "Playing music now"
pygame.init()
pygame.mixer.music.load('01ANightOfDizzySpells.mp3')
print "load song1"
pygame.mixer.music.play(loops=0, start=0.0)
print "play song1"
pygame.mixer.music.queue('01HHavok-intro.mp3')
pygame.mixer.music.queue('02HHavok-main.mp3')
pygame.mixer.music.queue('02Underclockedunderunderclockedmix.mp3')
pygame.mixer.music.queue('03ChibiNinja.mp3')
pygame.mixer.music.queue('04AllofUs.mp3')
pygame.mixer.music.queue('05ComeandFindMe.mp3')
pygame.mixer.music.queue('06Searching.mp3')
pygame.mixer.music.queue('07WeretheResistors.mp3')
pygame.mixer.music.queue('08Ascending.mp3')
pygame.mixer.music.queue('09ComeandFindMe-Bmix.mp3')
pygame.mixer.music.queue('10Arpanauts.mp3')
pygame.mixer.music.queue('DigitalNative.mp3')
pygame.mixer.music.set_endevent()
#musicPlayer()
musicPlayer()
Am I missing something basic? Or could it have to do with my computer not the code?
Edit: this is the output from running the code
Playing music now
load song1
play song1
As you can see it throws no errors.
I tried your code with a mid file, it works fine, but there's some adjustments:
import pygame
def musicPlayer():
pygame.init()
pygame.mixer.music.load('test.mid')
print "load song1"
pygame.mixer.music.play()
print "play song1"
pygame.mixer.music.queue('test_2.mid')
musicPlayer()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
print "DONE"
if the script ends the play won't happend, for that you need to get_busy() in a while loop.
in the documentation of pygame.music it states: Be aware that MP3 support is limited [...] Consider using OGG instead.
I played a little with the Sound class.
Here's what I came up:
import pygame
def musicPlayer():
pygame.mixer.init()
channel = pygame.mixer.Channel(1)
sound = pygame.mixer.Sound('test.ogg')
channel.play(sound)
musicPlayer()
while pygame.mixer.get_busy():
pygame.time.Clock().tick(10)
print "DONE"
I'm not very familiar with pygame and its methods, but my guess is that either it cannot find the file correctly, or it's not able to correctly handle the file that it finds.
I would suggest putting the full path to audio files to see if that helps. That would rule out the issue of it not finding the files properly (although hardcoding this is obviously not a good idea long-term as any changes you make to the organizational structure of your program will likely break those paths).
And according to their documentation, their MP3 support is limited. You might try using .ogg files instead (http://www.pygame.org/docs/ref/music.html) as it could just be an issue with the encoding not being fully supported.
Can someone help me load an image? It says "error: can't open tux.jpg:
import sys, pygame
pygame.init()
size = width, height = 600,400
screen = pygame.display.set_mode(size)
tux = pygame.image.load("tux.jpg")
screen.blit(tux,(200,200)) #Displays Tux On Screen
pygame.display.flip()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:sys.exit()
Please check that you have the image file within the directory that you are working in.
Using an absolute path may also be an option, for example:
tux = pygame.image.load("C:\\path\\to\\game\\tux.jpg")
For more information, please see this answer here.
The path you entered comes out as "./tux.png", i.e. the current working directory. Either place the file at the same location as your .py file (hence the default working directory for the script) or define the path to your image file.
For game file ordering, images are often in separate directories to the game scripts, The best way to do this is the os module. os.getcwd() gives the current working directory, and can be modified to the image directory using os.path.join. e.g.
game/
game.py
images/
tux.jgp
game.py uses pygame.load(os.path.join(os.getcwd(), "images")
(or define a datapath variable at the top in the same way if using lots of images!)