Omxplayer fill mode not working - python

Working on a video project for raspberry pi. Trying to get video to fill entire screen. When I call omxplayer videofile.mp4 --aspect-mode fill it plays fine. However when I call it in my program the argument for the aspect ratio is not working.
import pygame
import sys
from time import sleep
from omxplayer import OMXPlayer
pygame.joystick.init()
_joystick_right = pygame.joystick.Joystick(0)
_joystick_right.init()
_joystick_left = pygame.joystick.Joystick(1)
_joystick_left.init()
pygame.init()
done = False
button = ''
controller = ''
player = ''
path = 'hankvids/'
movies = [
'vid1.mp4',
'vid2.mp4',
]
quit_video = False
while done==False:
for event in pygame.event.get():
if event.type == pygame.JOYBUTTONDOWN:
button = event.button
controller = event.joy
if quit_video == True:
if button == 0 and controller == 0:
player.quit()
quit()
else:
if player.is_playing():
player.load(path + movies[controller], pause=False)
else:
quit_video = True
player = OMXPlayer(path + movies[controller], args=["-b --aspect-mode fill"], pause=False)

You need to split the command into words: args=["-b", "--aspect-mode", "fill"],. Alternatively you can pass your CLI string to shlex to split the args string for you.

Related

how to print after button is up?

using pygame, when i execute the program, all i want to do is to keep printing "mode 1". If i press button number 7 on the joystick, i want it to print "mode 2" only after button 7 has been UP (meaning pressed then released). If i press button 7 again, i want it to print "mode 1" again. I tried using pygame.JOYBUTTONDOWN and pygame.JOYBUTTONUP but it just doesnt work and the best code i can come up with is the following:
Result: it prints "mode 1".....then it prints "mode 2" only if i keep holding button 7 :( if i let go of button 7, it just goes back to printing "mode 1"
import sys
import pygame
import time
from pygame.locals import *
pygame.init()
global data_of_axis
def main():
global data_of_axis
gui_screen = pygame.display.set_mode((500, 700))
pygame.display.set_caption("Joystick example")
joysticks = {}
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True # Flag that we are done so we exit this loop.
# Handle hotplugging
if event.type == pygame.JOYDEVICEADDED:
# This event will be generated when the program starts for every
# joystick, filling up the list without needing to create them manually.
joy = pygame.joystick.Joystick(event.device_index)
joysticks[joy.get_instance_id()] = joy
#print("Joystick {} connencted".format(joy.get_instance_id()))
if event.type == pygame.JOYDEVICEREMOVED:
del joysticks[event.instance_id]
#print("Joystick {} disconnected".format(event.instance_id))
for joystick in joysticks.values():
butt7Down = joystick.get_button(7)
if butt7Down:
print("mode 2")
else:
print("mode 1")
time.sleep(0.1)
pygame.display.update()
if __name__ == "__main__":
main()
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()
One way to do this is to watch for a Joystick button event, and then re-read the status of all joystick buttons. Whenever the new set of states is read, make a copy of the set, to notice changes between "before" and "now".
This allows the code to simply check if the previous state was pressed, but now it isn't, and then print the appropriate output string.
# Create a list of "released" button states
button_states = [ False for i in range( joystick.get_numbuttons() ) ]
prev_states = button_states.copy()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.JOYBUTTONDOWN or \
event.type == pygame.JOYBUTTONUP:
prev_states = button_states.copy() # make a copy of the previous states
# Whenever we see a joystick event, re-read the status of all buttons
button_states = [ joystick.get_button( i ) for i in range( joystick.get_numbuttons() ) ]
# [...]
# If there's enough button states
if len( button_states ) > 7 and \
len( prev_states ) > 7:
# If the button was pushed, but now is released
if prev_states[7] == True and button_states[7] == False:
print( "mode2" )
else:
print( "mode1" )

Pygame: Adding an Escape key to exit whole game with stopwatch function

I'm making a game via Python on a Raspberry Pi. I'm using the GPIOs to light up an LED and detect a button switch.
I wanted to incorporate an ESC on the keyboard so we can exit at any time.
But whenever I add in the ESC key code into the main while loop. It doesn't work. The LED and Buttons work, but when I press on the ESC key, it doesn't do anything.
The loop runs to refresh/run a stopwatch and listen to an LED button via the GPIO.
I wanted some advice on how things like ESC key are handled in games. Especially with fast paced games where the loop and cycles are very fast.
Any tips or suggestions would be greatly appreciated. Thanks in advance.
Please see the code below:
# Importing all libraries
import RPi.GPIO as GPIO
import sys, time, atexit, pygame
# Setup GPIO and Pygame
GPIO.setmode(GPIO.BCM)
pygame.init()
# Define Tuples and Variables
leds = (16,17,22,9,5)
switches = (19,4,27,10,11)
button_pressed = False
taskcomplete = False
# Pygame visual variables
screen = pygame.display.set_mode( (1024,240) )
counterfont = pygame.font.Font('DSEG14Modern-Regular.ttf', 70)
# Set Pygame refresh rate variable = clock
clock = pygame.time.Clock()
# Clock variables
sec_val = 0
sec = 0
mins = 0
hours = 0
# Status variables
paused = False
running = True
# Start the clock
start_time = pygame.time.get_ticks()
# Defining Functions
# Function that renders segment display on screen
def time_convert(sec):
sec = sec % 60
sec_val = ("Timer: {0}".format(round((sec), 2)))
counting_text = counterfont.render(str(sec_val), 3, (134,145,255))
counting_rect = counting_text.get_rect(left = screen.get_rect().left)
screen.fill( (0,0,0) )
screen.blit(counting_text, (300,40))
pygame.display.update()
# Stopwatch function to compute for a SS:MS based stopwatch
def stop_Watch():
end_time = time.time()
time_lapsed = end_time - start_time
sec_val = time_convert(time_lapsed)
# Press Button 1 to start the game
def but_3():
while GPIO.input(switches[2]) == GPIO.LOW:
GPIO.output(leds[2],True)
time.sleep(0.01)
stop_Watch()
GPIO.output(leds[2],False)
print(" Button 3 is pressed! Exit")
start_time = time.time()
def buttonPress(channel):
# This function gets called every time a button is pressed, if the button pressed is the same as the button
# that is illuminated, then we set the "correct_button" variable to True,
# otherwise we set the "incorrect_button" variable to True.
# We need to set some variables to global so that this function can change their value.
button_pressed = True
def exit():
# This function gets called when we exit our script, using Ctrl+C
print("GPIO Clean Up!")
GPIO.cleanup()
pygame.quit()
# This tells our script to use the "exit()" without this, our "exit()" function would never be called.
atexit.register(exit)
#Loop through the leds to set them up
for led in leds:
# Set the led to be an ouput
GPIO.setup(led, GPIO.OUT)
# Turn the led off
GPIO.output(led,False)
# Loop through the switches to set them up
for switch in switches:
# Set the switch to be an input
GPIO.setup(switch, GPIO.IN)
# Add rising edge detection
GPIO.add_event_detect(switch, GPIO.RISING, bouncetime=300)
# Add the function "buttonPress" to be called when switch is pressed.
GPIO.add_event_callback(switch, buttonPress)
# Main sequence code
# Setup Pygame refresh rate to 120 fps
clock.tick(120)
# Start timer
start_time = time.time()
# Main loop
while running:
# Press Button 1 to start the game
while GPIO.input(switches[0]) == GPIO.LOW:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
print("escape pressed")
running = False
GPIO.output(leds[0],True)
time.sleep(0.01)
stop_Watch()
GPIO.output(leds[0],False)
print(" Button 1 is pressed! Exit")
running = False
exit()
It's because it's in another while loop I'm guessing, so it's not in the running while loop anymore. You can add pygame.quit() to make it quit that way though:
# Main loop
while running:
# Press Button 1 to start the game
while GPIO.input(switches[0]) == GPIO.LOW:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
print("escape pressed")
pygame.quit()
running = False
GPIO.output(leds[0],True)
time.sleep(0.01)
stop_Watch()
GPIO.output(leds[0],False)
print(" Button 1 is pressed! Exit")
running = False
exit()
Or, since you have a function named exit() that does the same thing, you can add exit() to those places instead.

PyGame - RaspberryPi 3b+ with a ps3 controller

I am trying to use pygame with the raspberry pi to use a PlayStation 3 controller as an input for a car.
I have tested the controller with a demo code, and everything works fine. Then when I try to use it in my program, it reads 0.0 as the input, when the joysticks are moved. attached is my current code:
import pygame
class controller:
def __init__(self):
pygame.init()
pygame.joystick.init()
global joystick
joystick = pygame.joystick.Joystick(0)
joystick.init()
def get_value(self, axis):
value = joystick.get_axis(axis)
return value
control = controller()
val = control.get_value(0)
while True:
print(val)
I am aware that this test is only for axis 0, but the output is still 0.0 for all axes.
Below, i have attached the demo code, where all the values are properly read.
import pygame, sys, time #Imports Modules
from pygame.locals import *
pygame.init()#Initializes Pygame
pygame.joystick.init()
joystick = pygame.joystick.Joystick(0)
joystick.init()#Initializes Joystick
# get count of joysticks=1, axes=27, buttons=19 for DualShock 3
joystick_count = pygame.joystick.get_count()
print("joystick_count")
print(joystick_count)
print("--------------")
numaxes = joystick.get_numaxes()
print("numaxes")
print(numaxes)
print("--------------")
numbuttons = joystick.get_numbuttons()
print("numbuttons")
print(numbuttons)
print("--------------")
loopQuit = False
while loopQuit == False:
# test joystick axes and prints values
outstr = ""
for i in range(0,4):
axis = joystick.get_axis(i)
outstr = outstr + str(i) + ":" + str(axis) + "|"
print(outstr)
# test controller buttons
outstr = ""
for i in range(0,numbuttons):
button = joystick.get_button(i)
outstr = outstr + str(i) + ":" + str(button) + "|"
print(outstr)
for event in pygame.event.get():
if event.type == QUIT:
loopQuit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
loopQuit = True
# Returns Joystick Button Motion
if event.type == pygame.JOYBUTTONDOWN:
print("joy button down")
if event.type == pygame.JOYBUTTONUP:
print("joy button up")
if event.type == pygame.JOYBALLMOTION:
print("joy ball motion")
# axis motion is movement of controller
# dominates events when used
if event.type == pygame.JOYAXISMOTION:
# print("joy axis motion")
time.sleep(0.01)
pygame.quit()
sys.exit()
any feedback will be much appreciated.
The code is losing the reference to the initialised joystick. It needs to maintain an internal link to it. Note the use of self. in the class below. This keeps the reference inside the class, making "self.joystick" a member variable of the class. Python classes need the self. notation (unlike lots of (all?) other object orientated languages). While editing I changed some of the names to match the Python PEP-8 style guide, I hope that's OK ;)
class Controller:
def __init__( self, joy_index=0 ):
pygame.joystick.init() # is it OK to keep calling this?
self.joystick = pygame.joystick.Joystick( joy_index )
self.joystick.init()
def getAxisValue( self, axis ):
value = self.joystick.get_axis( axis )
return value
Maybe you left the extra code out of the question, but a PyGame program without an event loop will eventually lock up.
import pygame
# Window size
WINDOW_WIDTH = 300
WINDOW_HEIGHT = 300
class Controller:
""" Class to interface with a Joystick """
def __init__( self, joy_index=0 ):
pygame.joystick.init()
self.joystick = pygame.joystick.Joystick( joy_index )
self.joystick.init()
def getAxisValue( self, axis ):
value = self.joystick.get_axis( axis )
return value
### initialisation
pygame.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
clock = pygame.time.Clock()
pygame.display.set_caption( "Any Joy?" )
# Talk to the Joystick
control = controller()
# Main loop
done = False
while not done:
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
# Query the Joystick
val = control.getAxisValue( 0 )
print( "Joystick Axis: " + str( val ) )
# Update the window, but not more than 60fps
window.fill( (0,0,0) )
pygame.display.flip()
clock.tick_busy_loop(60)
pygame.quit()

Pygame not reading any values from PS3 controller

I have been trying to set up a PS3 controller and be able to read analog input values from it, but whenever I press down or move any of the joysticks it doesn't read anything and returns false for everything.
I have been using various test codes I have found online for the controller and none of them seem to work. I'm starting to think it may be a hardware issue, but I'm still unsure.
import os
import pprint
import pygame
class PS3Controller(object):
controller = None
name = None
axis_data = None
button_data = None
hat_data = None
def init(self):
"""Initialize the joystick components"""
pygame.init()
pygame.joystick.init()
self.controller = pygame.joystick.Joystick(1)
self.controller.init()
def listen(self):
"""Listen for events to happen"""
if not self.axis_data:
self.axis_data = {}
if not self.button_data:
self.button_data = {}
for i in range(self.controller.get_numbuttons()):
self.button_data[i] = False
if not self.hat_data:
#D - Pad
self.hat_data = {}
for i in range(self.controller.get_numhats()):
self.hat_data[i] = (0, 0)
while True:
for event in pygame.event.get():
if event.type == pygame.JOYAXISMOTION:
self.axis_data[event.axis] = round(event.value, 2)
elif event.type == pygame.JOYBUTTONDOWN:
self.button_data[event.button] = True
elif event.type == pygame.JOYBUTTONUP:
self.button_data[event.button] = False
elif event.type == pygame.JOYHATMOTION:
self.hat_data[event.hat] = event.value
# Insert your code on what you would like to happen for each event here!
# In the current setup, I have the state simply printing out to the screen.
#os.system('clear')
#pprint.pprint(self.button_data)
pprint.pprint(self.axis_data)
#pprint.pprint(self.hat_data)
if __name__ == "__main__":
ps3 = PS3Controller()
ps3.init()
ps3.listen()
The code works fine. Apparently, I had to download a specific set of drivers to make the PS3 controller compatible with windows so it could be read as an XBOX 360 controller.
There were some tutorials online that used SCP ToolKit driver installer to make the controller compatible, however, it did make it so I couldn't use my Bluetooth mouse for some reason.

for event in pygame.event.get(): pygame.error: video system not initialized when using ssh

Here is the code that I'm trying to run via ssh into my raspberry pi. It usually works fine when I have a keyboard and monitor connected directly to the raspberry pi, but it doesn't run when I am using ssh.
import pygame, sys, time
from pygame.locals import *
pygame.init()
pygame.joystick.init()
joystick = pygame.joystick.Joystick(0)
joystick.init()
#screen = pygame.display.set_mode((400,300))
#pygame.display.set_caption('Hello World')
interval = 0.01
# get count of joysticks=1, axes=27, buttons=19 for DualShock 3
joystick_count = pygame.joystick.get_count()
print("joystick_count")
print(joystick_count)
print("--------------")
numaxes = joystick.get_numaxes()
print("numaxes")
print(numaxes)
print("--------------")
numbuttons = joystick.get_numbuttons()
print("numbuttons")
print(numbuttons)
wprint("--------------")
loopQuit = False
while loopQuit == False:
# test joystick axes
# outstr = ""
# for i in range(0,4):
# axis = joystick.get_axis(i)
# outstr = outstr + str(i) + ":" + str(axis) + "|"
# print(outstr)
# test controller buttons
outstr = ""
for i in range(0,numbuttons):
button = joystick.get_button(i)
outstr = outstr + str(i) + ":" + str(button) + "|"
print(outstr)
for event in pygame.event.get():
if event.type == QUIT:
loopQuit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
loopQuit = True
The error that I am getting is
Traceback (most recent call last):
File "testing_joystick.py", line 47, in
for event in pygame.event.get():
pygame.error: video system not initialized
Can anyone help me figure out how to get around this error please?
I know it's been a while since the question has been posted, but I faced the same problem today.
For me the sudo command resolved the ssh problem.
sudo python code_path.py
I had a similar issue as described. The problem appears when no X server is available, that's why it works when you have a monitor connected to the Raspberry.
A solution is to run ssh with the X forwarding option:
ssh -X pi#raspberry_ip_address
Then your program should run as normal:
python your_code.py
Hope this helps anybody else.
Well you have not initialized your window yet. It looks like you may or may not have commented it out: #screen = pygame.display.set_mode((400, 300)). Many of pygame's events rely on the window. Simply un-comment your screen initialization and it should work fine.

Categories