Writing in console works, scripts don't - python-3.x

I'm new to Python3 and I tried to use pygame library. Firstly I tried to play .mp3 file using pygame.mixer with following code:
import pygame
from pygame import mixer
mixer.init()
mixer.music.load('some.mp3')
mixer.music.play()
I tried to run this code but it just went through it and didn't do anything but showed pygame welcome message. Not even a single error. Then I tried to run this code by writing every single line in console and somehow it worked.
Similar thing happens with this code:
from pygame import *
init()
while going:
for e in event.get():
if e.type == QUIT:
going = False
if e.type == KEYDOWN:
if e.key == K_ESCAPE:
going = False
print("work")
I copied it from official pygame eventlist example and while the example runs as it's intended to it doesn't work when I use only part showed above.
What am I doing wrong here?

You haven't told your program to write anything so it hasn't.
You need to to add print statements if you want your Python program to write something to your console.
Here's an example:
print("Hello World")
You should obviously place the exact response you are looking to get inside the print statement.

Related

Pygame Mixer gives Couldn't open audio device on Azure ML [duplicate]

I'm trying to play sound files (.wav) with pygame but when I start it I never hear anything.
This is the code:
import pygame
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("desert_rustle.wav")
sounda.play()
I also tried using channels but the result is the same
For me (on Windows 7, Python 2.7, PyGame 1.9) I actually have to remove the pygame.init() call to make it work or if the pygame.init() stays to create at least a screen in pygame.
My example:
import time, sys
from pygame import mixer
# pygame.init()
mixer.init()
sound = mixer.Sound(sys.argv[1])
sound.play()
time.sleep(5)
sounda.play() returns an object which is necessary for playing the sound. With it you can also find out if the sound is still playing:
channela = sounda.play()
while channela.get_busy():
pygame.time.delay(100)
I had no sound from playing mixer.Sound, but it started to work after i created the window, this is a minimal example, just change your filename, run and press UP key to play:
WAVFILE = 'tom14.wav'
import pygame
from pygame import *
import sys
mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096)
pygame.init()
print pygame.mixer.get_init()
screen=pygame.display.set_mode((400,400),0,32)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key==K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key==K_UP:
s = pygame.mixer.Sound(WAVFILE)
ch = s.play()
while ch.get_busy():
pygame.time.delay(100)
pygame.display.update()
What you need to do is something like this:
import pygame
import time
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("desert_rustle.wav")
sounda.play()
time.sleep (20)
The reason I told the program to sleep is because I wanted a way to keep it running without typing lots of code. I had the same problem and the sound didn't play because the program closed immediately after trying to play the music.
In case you want the program to actually do something just type all the necessary code but make sure it will last long enough for the sound to fully play.
import pygame, time
pygame.mixer.init()
pygame.init()
sounda= pygame.mixer.Sound("beep.wav")
sounda.play()
pygame.init() goes after mixer.init(). It worked for me.
I had the same problem under windows 7. In my case I wasn't running the code as Administrator. Don't ask me why, but opening a command line as administrator fixed it for me.
I think what you need is pygame.mixer.music:
import pygame.mixer
from time import sleep
pygame.mixer.init()
pygame.mixer.music.load(open("\windows\media\chimes.wav","rb"))
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
sleep(1)
print "done"
You missed to wait for the sound to finish. Your application will start playing the sound but will exit immediately.
If you want to play a single wav file, you have to initialize the module and create a pygame.mixer.Sound() object from the file. Invoke play() to start playing the file. Finally, you have to wait for the file to play.
Use get_length() to get the length of the sound in seconds and wait for the sound to finish:
(The argument to pygame.time.wait() is in milliseconds)
import pygame
pygame.mixer.init()
sounda = pygame.mixer.Sound('desert_rustle.wav')
sounda.play()
pygame.time.wait(int(sounda.get_length() * 1000))
Alternatively you can use pygame.mixer.get_busy to test if a sound is being mixed. Query the status of the mixer continuously in a loop.
In the loop, you need to delay the time by either pygame.time.delay or pygame.time.Clock.tick. In addition, you need to handle the events in the application loop. See pygame.event.get() respectively pygame.event.pump():
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
import pygame
pygame.init()
pygame.mixer.init()
sounda = pygame.mixer.Sound('desert_rustle.wav')
sounda.play()
while pygame.mixer.get_busy():
pygame.time.delay(10)
pygame.event.poll()
Your code plays desert_rustle.wav quite fine on my machine (Mac OSX 10.5, Python 2.6.4, pygame 1.9.1). What OS and Python and pygame releases are you using? Can you hear the .wav OK by other means (e.g. open on a Mac's terminal or start on a Windows console followed by the filename/path to the .wav file) to guarante the file is not damaged? It's hard to debug your specific problem (which is not with the code you give) without being able to reproduce it and without having all of these crucial details.
Just try to re-save your wav file to make sure its frequency info. Or you can record a sound to make sure its frequency,bits,size and channels.(I use this method to solve this problem)
I've had something like this happen. Maybe you have the same problem? Try using an absolute path:
import pygame
pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("/absolute_path/desert_rustle.wav")
sounda.play()
Where abslute_path is obviously replaced with your actual absolute path ;)
good luck.
import pygame
pygame.init()
sound = pygame.mixer.Sound("desert_rustle.wav")
pygame.mixer.Sound.play(sound)
This will work on python 3
5 years late answer but I hope I can help someone.. :-)
Firstly, you dont need the "pygame.init()"-line.
Secondly, make a loop and play the sound inside that, or else pygame.mixer will start, and stop playing again immediately.
I got this code to work fine on my Raspberry pi with Raspbian OS.
Note that I used a while-loop that continues to loop the sound forver.
import pygame.mixer
pygame.mixer.init()
sounda = pygame.mixer.Sound("desert_rustle.wav")
while True:
sounda.play()
Just try:
import pygame.mixer
from time import sleep
pygame.mixer.init()
pygame.mixer.music.load(open("\windows\media\chimes.wav","rb"))
print ""
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
sleep(1)
print "done"
This should work. You just need to add print ""and the sound will have
had time to load its self.
Many of the posts are running all of this at toplevel, which is why the sound may seem to close. The final method will return while the sound is playing, which closes the program/terminal/process (depending on how called).
What you will eventually want is a probably a class that can call either single time playback or a looping function (both will be called, and will play over each other) for background music and single sound effects.
Here is pattern, that uses a different event loop / run context other than Pygame itself, (I am using tkinter root level object and its init method, you will have to look this up for your own use case) once you have either the Pygame.init() runtime or some other, you can call these methods from your own logic, unless you are exiting the entire runtime, each file playback (either single use or looping)
this code covers the init for ONLY mixer (you need to figure our your root context and where the individual calls should be made for playback, at least 1 level inside root context to be able to rely on the main event loop preventing premature exit of sound files, YOU SHOULD NOT NEED TIME.SLEEP() AT ALL (very anti-pattern here).... ALSO whatever context calls the looping forever bg_music, it will probably be some 'level' or 'scene' or similar in your game/app context, when passing from one 'scene' to the next you will probably want to immediately replace the bg_music with the file for next 'scene', and if you need the fine-grained control stopping the sound_effect objects that are set to play once (or N times)....
from pygame import mixer
bg_music = mixer.Channel(0)
sound_effects = mixer.Channel(1)
call either of these from WITHIN your inner logic loops
effect1 = mixer.Sound('Sound_Effects/'+visid+'.ogg')
sound_effects.play(effect1, 0)
sound1 = mixer.sound('path to ogg or wav file')
bg_music.play(sound1, -1) # play object on this channel, looping forever (-1)
do this:
import pygame
pygame.mixer.init()
pygame.mixer.music.load("desert_rustle.wav")
pygame.mixer.music.play(0)
I think that your problem is that the file is a WAV file.
It worked for me with an MP3. This will probably work on python 3.6.

How do I run other python separate inside of kivy program

Coming from Arduino to python I am use to everything running in a loop more or less.
I am trying to understand how python interacts with kivy.
I understand that in order to make a segment of code run over and over I need a while statement for example. However if I use code that loops before it gets to the kivy code it will never get to the kivy code. But if I make a loop after the kivy code it will not run till I close the program.
I have google around and I see examples of simple projects of python/kivy projects that all the code pertains to the UI glue logic to make it actually do something. But I have not seen anything show python code running independent of the kivy project.
In other words if I made a project in Arduino I would have a main loop and I could call out to functions and then return from them. However I don't understand what is the best way to do this with kivy/python.
The sample code I have posted below is not a loop however I would expect it to run everything in one go. But It will run the first print statements and then when I close the app the last print statement will run.
I understand that loops are not recommended with object oriented programing, this is just a simple example as reference of what I'm use to.
For those that will say I don't understand what your asking and what are you trying to do or ask?
I am trying to ask where do I put python code that dose not pertain immediately to the kivy code but needs to run in loops or whatever while kivy is running. So that I can make things happen on the python side while not blocking kivy.
Dose this require multiple python programs? And leave the kivy program by itself almost like a .kv file.
Or dose it require everything to be put in classes?
Thanks for any clarification, best practices or examples.
from kivy.app import App
from kivy.uix.button import Button
print("test")
class FirstKivy(App):
def build(self):
return Button(text="Test text")
print("test2")
FirstKivy().run()
print("test3")
You would need to add Threading to your code
from kivy.app import App
from kivy.uix.button import Button
import threading
print("test")
class FirstKivy(App):
def build(self):
return Button(text="Test text")
print("test2")
def run():
FirstKivy().run()
def print_stuff():
print("test3")
kivy_thread = threading.Thread(target=run)
print_thread = threading.Thread(target=print_stuff)
kivy_thread.start()
print_thread.start()

Python multiprocessing refuses to execute code and exits instantly

I was working on a larger piece of code and I kept getting an error when the program just seemed to end without doing anything. I narrowed down the problem and reproduced it below. As far as I understand the code should print the sentence and it seems to work on other online IDE's while failing on mine. Feel like I'm missing something super simple.
Failing On: IDLE Python 3.8.3 32-bit from python.org
Works On: onlinegdb.com
Code:
import multiprocessing
def x():
print("This is x func")
if __name__ == '__main__':
multiprocessing.freeze_support()
p = multiprocessing.Process(target=x)
p.start()
p.join()
Output:
>>>
I think the issue is IDLE just doesn't output stuff from stuff outside the main process. Need to use consoles which would output everything from the main and all other processes. Reference : Python multiprocessing example not working

Why is there no response when i call the function in the if statement?

Hi I'm new to python and my first project is to create a GUI app with a few buttons to play songs. The problem is in the if statement, VLC will not play the file no matter what i do. This if statement worked in another program only running in the Terminal.
import vlc
import easygui
x = easygui.buttonbox(choices=("x","y","z"))
if x == "y":
p = vlc.MediaPlayer("/directory/to/mp3/file")
p.play()
Looking at the documentation for easygui it appears that the choices for a buttonbox are stored as a list and not as a tuple. Try easygui.buttonbox(choice=["x","y","z"]) instead.

Why does X choke after I draw to the root window

For background, I'm running
Debian Lenny, and have tried this with both GNOME and Fluxbox.
Anyway, I've been looking at how to draw on the desktop, and I found and tried this code here:
http://blog.prashanthellina.com/2007/08/24/drawing-on-your-desktop/
It worked fine, except upon terminating it (by hitting control C), X loses it's ability to create new windows.
I had thought that maybe the problem was pygame not releasing some resource, so I added in a block of code to trap the kill signal, giving me the following:
"""
Run the following command in the shell before executing this script
export SDL_WINDOWID=`xwininfo -root|grep "id:"|sed 's/^.*id: //'|sed 's/ (.*$//'`
"""
import pygame
import sys
import random
import time
import signal
pygame.init()
window = pygame.display.set_mode((1280, 1024))
screen = pygame.display.get_surface()
def handle_sigint(signum, frame):
"""I want to ensure resources are released before bailing."""
print("SIGINT received.");
pygame.display.quit()
pygame.quit()
sys.exit(0)
# Set handler to catch C^C Interupts
signal.signal(signal.SIGINT, handle_sigint)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit(0)
x = random.choice(range(640))
y = random.choice(range(480))
radius = random.choice(range(100))
col_r = random.choice(range(255))
col_g = random.choice(range(255))
col_b = random.choice(range(255))
time.sleep(.03)
rect = pygame.draw.circle(screen, (col_r, col_g, col_b), (x,y), radius)
pygame.display.update(rect)
And so I tried again. The print statement in the interrupt handler tells me that the handler does run when I quit, but I still have the same problem. And even more interestingly, X has no problems while it's running. It's only after terminating it.
Might anybody out there have any idea what's happening, and what I can do to fix the code so it doesn't wreck my X session? Thanks in advance.
Questions, ideas & things to try:
If you have a terminal up before you try a -c, can you still type in it after? If yes, there's likely a problem in your session or window manager, not the x server.
Have you tried Ctrl-Alt-Backspace? Does this fix your problem?
Are gtk-window-decorator and x-session-manager still running?
pygame is typically run out of a window and is normally going to try to cleanup after itself. You've added an explicit call to pygame.display.quit(), but I don't think this changes anything - pygame tries to delete the window referred to by the SDL_WINDOWID variable. Actually succeeding in deleting your root window is probably a bad thing. I'm going to guess that the guy you got this from, running ubuntu, pygame fails to delete the window because he doesn't have permission. You might on your OS.
Since killing your root window is bad, how about just restoring control of the root window back to nautilus (gnome)? something like gconftool-2 --type bool --set /apps/nautilus/preferences/show_desktop true?

Resources