Qmediaplayer setposition QtPython - python

I am trying to set up a simple media player with Qt.
I want to choose the start position of the video on startup of the player. I bound this to an isSeekable event to make sure media is loaded and seekable.
Still the player does not work as expected. Either I am gettings errors (0xC00D6D60) or the video just starts from the beginning.
This is my code:
def seekable_changed(self, is_seekable):
if (is_seekable):
self._player.pause()
self._player.setPosition(videostartmsdiff) # milliseconds
self._player.play()
I tried different combinations with or without pause() and play()
How do I set start position in Qt to let it work as expected?
Thanks

You should connect to QMediaPlayer::stateChanged(QMediaPlayer::State state) signal and call setPosition when state becomes QMediaPlayer::PlayingState.

Related

How intercept mouse device with Python for Games?

I trying to move my mouse inside an FPS game (like valorant/csgo) but doesn't work.
I used PyAutoGui, PyInput, Mouse, PyWin32, and many other libs but I just can simulate a click.
I see something about Interception (by oblitum) and years ago worked but this day doesn't. The game block this intercept.
So I guess I need to build some driver intercept to make moves in Mouse. Another trick is to use Arduino (this works these days) but for my project this isn't a solution. I need to only in python with any mouse.
This depends how you want to move your mouse. I'm assuming according to however you want to move it? If so, try the first code as the second code performs based on a series of commands
Have you tried this code by #flipeador?
#from interception import Interception, MouseFilter, KeyFilter, MouseFlags,\
# MouseState, KeyState, MapVk, Vk, map_virtual_key
RUNNING = True
TIMEOUT = 2500 # ms
interception = Interception()
interception.set_mouse_filter(MouseFilter.ButtonAll)
interception.set_keyboard_filter(KeyFilter.All)
while RUNNING:
device = interception.wait_receive(TIMEOUT)
if device:
print(f'{device.get_hardware_id()}:')
# Mouse
if device.is_mouse:
print('MouseStroke(flags={1},state={2},rolling={0.rolling},x={0.x},y={0.y},info={0.info})'
.format(device.stroke, MouseFlags(device.stroke.flags).name, MouseState(device.stroke.state).name))
# Keyboard
elif device.is_keyboard:
vk = map_virtual_key(device.stroke.code, MapVk.ScToVk)
print('KeyStroke(sc={0.code:03X},vk={2:03X},state={1},info={0.info})'
.format(device.stroke, KeyState(device.stroke.state).name, vk))
# escape = terminate
if vk == Vk.Escape:
RUNNING = False
# switch x and y
elif vk == Vk.X:
device.stroke.code = map_virtual_key(Vk.Y, MapVk.VkToSc)
elif vk == Vk.Y:
device.stroke.code = map_virtual_key(Vk.X, MapVk.VkToSc)
device.send()
print('-'*100)
Do note that you are not allowed to cheat in Valorant, as it blocks a lot of "hacking" and detect if your hacking even if the program your using is not on their block list.
I'm not here to question your morality.
Definitely go the arduino(s) route (you may need two. One to receive python commands and one to emulate the mouse events. Depends on the arduino) and be sure to use some randomization everywhere.
I do question why you'd want this.
I see no fun in cheating and I can't see what you are trying to achieve with this.
Although you said it did not work for you, the package you want to use is pynput. It is possible to simulate mouse movements and clicks as stated in the docs.
from pynput.mouse import Button, Controller
mouse = Controller()
# Move pointer relative to current position
mouse.move(5, -5)
This should give you the behaviour you want.
EDIT: with anti-cheat software in place, it may be very hard (not to say impossible) to simulate mouse movements in games. The game can distinguish organic mouse movement from simulated movement. Python alone might not be able to convince Valorant that your mouse movement is "real" ;)

python curses tty screen blink

I'm writing a python curses game (https://github.com/pankshok/xoinvader).
I found a problem: in terminal emulator it works fine, but in tty screen blinks.
I tried to use curses.flash(), but it got even worse.
for example, screen field:
self.screen = curses.newwin(80, 24, 0, 0)
Main loop:
def loop(self):
while True:
self.events()
self.update()
self.render()
render: (https://github.com/pankshok/xoinvader/blob/master/xoi.py#L175)
self.screen.clear()
#draw some characters
self.screen.refresh()
time.sleep(0.03)
Constant time in sleep function is temporary, until I write 60 render calls controller.
How to implement render method correctly?
Thanks in advance,
Paul.
Don't call clear to clear the screen, use erase instead. Using clear sets a flag so that when you call refresh the first thing it does is clear the screen of the terminal. This is what is causing the terminal's screen to appear to blink. The user sees the old screen, then a completely blank screen, then your new screen. If you use erase then it will instead modify the old screen to look like the new one.
You may still see some odd flashing or other artifacts on slow terminals. Try calling screen.idcok(False) and screen.idlok(False) to stop curses from using insert and deletion operations to update the screen.

Stop Winsound / Stop a thread on Python

Im writing a litle game on python using Tkinter (And by the way, i am not allowed to use any other non built in modules) and I want to play a background song when on the main window, wich is the one that holds the title, and the buttons to go to other windows and stuff...
So the thing is that I need that sound to stop when I enter to another window, but when I hit the button to go, to another window, the song keeps playing...
I'm using the winsound module, and had define a couple of functions, (That by the way, are wicked as hell) to play the song when I first run the program using threads...
So here is the deal, I want something to put in the function "killsound" so that I can add it to every button, and then when I press any button to open any other window, the sound will be killed.
I was hoping something like 'a.kill()' or 'a.stop()' but it didnt worked.
And I really don´t know how to use the SND_PURGE thing on winsound... Although I understand that SND_PURGE is no longer working on new windows OS (Got Win8.1)
Could you please help me?
Thank You! (And Sorry for the creepy english...)
def Play(nombre): #This function Is the core of the winsound function
ruta = os.path.join('Audio',nombre)
Reproducir= winsound.PlaySound(ruta,winsound.SND_FILENAME)
return Reproducir
def PlayThis():
while flag_play:
try:
return Play('prettiest weed.wav')
except:
return "Error"
def PlayThisThread():
global flag_play
flag_play= True
a=Thread(target=PlayThis, args=())
a.daemon = True
a.start()
PlayThisThread()
def killsound(): #This is the function I want, for killing sound.
global flag_play
flag_play = False
There are 2 major problems in your code:
global variable flag_play has to be placed inside the sound playback loop, in your case within the PlayThis() function
the Winsound module is aiming simple non-threaded usage. while the sound is playbacked, there is no chance to "softly" interrupt. It does not support any playback status reporting e.g. .isPlaying() nor any kind of .stop() that you need in order to kill it.
Solution:
try PyMedia package. Pymedia allows lower-level audio manipulation therefore more details have to be provided at the initialisation:
import time, wave, pymedia.audio.sound as sound
# little to do on the proper audio setup
f= wave.open( 'prettiest weed.wav', 'rb' )
sampleRate= f.getframerate() # reads framerate from the file
channels= f.getnchannels()
format= sound.AFMT_S16_LE # this sets the audio format to most common WAV with 16-bit codec PCM Linear Little Endian, use either pymedia or any external utils such as FFMPEG to check / corvert audio into a proper format.
audioBuffer = 300000 # you are able to control how much audio data is read
with the following assigment the "snd" becomes an instance of the class sound.Output and gives you bunch of useful audio methods:
snd= sound.Output( sampleRate, channels, format )
s= f.readframes( audioBuffer )
snd.play( s )
and finally your threaded playback loop might look as follows:
while snd.isPlaying():
global flag_play
if not flag_play: snd.stop() #here is where the playback gets interupted.
time.sleep( 0.05 )
f.close()
Please, let me know if you need more support on this.
I also created a 0.5 sec wavfile in Adobe Audition containing silence and attached it to the stop button, and this basically "stopped" playback of the previously played audio clip.
I found a way to do it, by adding a 0.5sec sound to a button, so that when I press the button it stops the background one to play the button one, and then stops all sounds on program.

Python using turtle button

I am attempting for a homework assignment to implement Simon Says in python. I'm trying to do it using the turtle library (a requirement).
However, I've run into a stumbling block in that while I can get the screen to register click events (currently just printing the x,y coordinates) I can't get it to wait for a click event.
Specifically what I'm planning on doing is having areas on the screen that when they click within that location it is considered as if they had clicked a button. Screen clears and game does whatever.
However, in experiments in trying to get a working 'button' all that it does is set it so it prints the x,y coordinates but the rest of the program finishes. Didn't wait for the user to click anything. I tried a blocking method of...
while clicked == False:
pass
or
while clicked == False:
time.sleep(1)
but both methods hangs the program until I manually interrupt and then it'll print the clicks.
Am I missing an option somewhere?
Turtles don´t have buttons, but they do have callbacks for clicks.
Furthermore, you should use onclick for Screen to detect general clicks and onclick for turtle to detect clicking in turtles. You can, for example, make a 4 BIG turtles with different colors by using a dynamic shape.
Also, turtle is based on Tk, so you must be aware of things like mainloop()
The following program give some hints for Python 2.7.5.
import turtle as t
from random import randint
class MyTurtle(t.Turtle) :
def __init__(self,**args) :
t.Turtle.__init__(self,**args)
def mygoto(self,x,y) :
t1.goto(x,y)
print x,y
def randonics(self,x,y) :
self.left(randint(90,270))
def minegoto(x,y) :
print x,y
t1.goto(x,y)
wt=t.Screen()
t1=MyTurtle()
wt.register_shape("big",((0,0),(30,0),(30,30),(0,30)))
t1.shape("big")
wt.onclick(t1.mygoto,btn=1)
wt.onclick(minegoto,btn=2)
t1.onclick(t1.randonics,btn=3)
t1.goto(100,100)
t.mainloop()
So after extensive search there isn't necessarily a way pause execution of the code in python while using turtle to wait for some click event. Maybe in Tk I could do that but not in turtle.
However, there is a way to get around that. As an example. A method sets up the fake button on the screen, sets the click event, and terminates. The click event when clicked calls the next method needed for execution. So until the button is clicked the actual code isn't doing anything but remains in memory for use.
So more specifically.
1. Create a 'button'.
2. Have your program behave normally until it needs to wait for a click event.
3. Set up the on screen click (or on turtle) in such a way when the 'button' is clicked the next part of the code is run.
Special note. The code in question can't depend on waiting for a click event for later on in code. Instead, the click causes the next part of the execution of your code.
You can make the function registered with onclick() test the x,y position. If it is inside some region you do whatever you must.
I don´t see the difference between what you want to do and what this code does, the modification of turtle position is just an example, you can do anything when a click is captured by onclick(), even start a thread if you really need it (using Creating Threads in python)
import turtle as t
from random import randint
from threading import Thread
from time import sleep
def threaded_function(arg,t1):
for i in range(arg):
print "running",i
sleep(1)
t1.forward(i*10)
def minegoto(x,y) :
print x,y
t1.goto(x,y)
thread = Thread(target = threaded_function, args = (10,t1 ))
thread.start()
thread.join()
print "thread finished...exiting"
wt=t.Screen()
t1=t.Turtle()
wt.register_shape("big",((0,0),(30,0),(30,30),(0,30)))
t1.shape("big")
wt.onclick(minegoto,btn=1)
t1.goto(100,100)
t.mainloop()

How to create a "play again" option with Pygame

I am new to programming with Python. I have been working through a tutorial book that I found, and got the game up and running, but then decided I wanted to have a "Play Again?" option at the end. I can get the game to quit out with a press of the "n" key, but cannot work out how to get the game to restart.
Here is the code I think is giving the trouble:
#player reaches treasure
if player_rectangle.colliderect(treasure_rectangle):
#display text
screen.blit(text,(screen_width/2-195,screen_height/2-25))
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_n:
exit()
elif event.key==pygame.K_y:
pygame.display.update()
I know something needs to go after the elif event, and I have tried all that I can think of. I tried to define the whole program, and call it but that stopped the whole thing running. I have looked around internet sites, but just cannot seem to come up with a answer.
Can some one help out in easy terms how to get the game to restart to the starting position when the y key is pressed? I know it has something to do with a loop, I just cannot place my finger on what.
Many thanks.
It's not entirely clear how your code is organized, so I'll be very general. Usually games are implemented with a "main loop" that handles all of the action. In "pseudo"-python:
def main_loop():
while True:
handle_next_action()
draw_screen()
if game_is_over():
break
Before you start the loop, you usually do some setup to get the game state how you want it:
def main():
setup()
main_loop()
shut_down()
Given those parts, you can reset the game by having the main loop code call setup again (it may need to be specifically designed to be runable more than once):
def main_loop():
while True:
handle_events()
draw_screen()
if game_is_over():
if play_again(): # new code here!
setup()
else:
break
You might want to split the setup code into two parts, one which only needs to be run when the program begins (to read configuration files and set up things like the window system), and a second that gets repeated for each new game (setting up the game's state).
To restart a game you normally need to reset all variables to their initial value (e.g. number of lives, score, initial position, ...).
The best way is to put all initialisations inside a procedure:
def init():
global score,lives # use these global variables
score=0
lives=3
init() # call init() to define and reset all values
while 1: # main loop
...
elif event.key==pygame.K_y:
init() # restart the game

Categories

Resources