Spotipy request speed in while loop - python

count = 0
while True:
if count > 20:
count = 0
current_track = spotify.current_user_playing_track()
if current_track is None:
display_string = ""
else:
display_string = current_track['item']['name']+" - "+current_track['item']['artists'][0]['name']+" | "
if display_string != previous_track:
sphd.clear()
sphd.write_string(display_string,brightness=0.1)
previous_track = display_string[:]
time.sleep(0.05)
sphd.show()
sphd.scroll(1)
count += 1
The code above is run on a Pi Zero to get the currently playing track every second and display it on a scrollphathd display. The problem is that the process of getting the track causes the display to freeze for about 0.25s. Is there any way of running the loop to get the track separately to refreshing the display's scrolling or any way to speed up getting the track? Thanks for any help in advance.

Possibly the reason of that freeze is the low performance that the Raspberry Pi Zero has.

Related

Moviepy doubles the speed of the video without affecting audio. I suspect a framerate issue but I havent been able to fix it

Right now here is all I'm having moviepy do:
full_video = VideoFileClip(input_video_path)
full_video.write_videofile("output.mp4")
quit()
It just takes the video and writes it to another file with no changes. But when the input video looks like this the output ends up looking like this with the video speed doubled but the audio just the same. I could take the audio and video separately, halve the speed of the video then put them back together but is there a way I can correct for whatever problem is causing this?
edit 2: It is the VideoFileClip method causing the speedup most likely, not the write_videofile method. When I try
full_video = VideoFileClip(input_video_path)
print( full_video.fps )
full_video.preview(fps = full_video.fps)
quit()
it is still double speed in the preview.
edit 3: The problem only happens with videos captured with Windows game bar. I tried a different video and it worked just fine with no speedup. I'll probably just find a different way to capture the screen recordings to fix it but I dont know what the root problem was
edit 1: the full code
from moviepy.editor import *
# get all dash times
times_path = "times.txt"
input_video_path = "input.mp4"
offset_time = 0
clip_length = float( input("Enter clip length: ") )
def get_times(path, offset):
dash_times_str = []
with open(path, "r") as file:
dash_times_str = file.readlines()
count = 0
# Strips the newline character
# also add offset time
temp = []
for line in dash_times_str:
count += 1
temp.append ("{}".format(line.strip()))
dash_times_str = temp
dash_times = []
for time in dash_times_str:
dash_times.append( float(time) + offset )
return dash_times
dash_times = get_times(times_path, offset_time)
def get_offset_time():
a = float(input("Enter time for first dash in video"))
b = dash_times[0]
return a-b
offset_time = get_offset_time()
full_video = VideoFileClip(input_video_path)
counter = 0
times_count = len(dash_times)
clips = []
for dash_time in dash_times:
clip = full_video.subclip(dash_time,dash_time+clip_length)
clips.append(clip)
counter+=1
print("Clip " + str(counter) + " out of " + str(times_count))
final_clip = concatenate_videoclips(clips)
final_clip.write_videofile("output.mp4")
I haven't been able to go deep down in the source code to figure out why this is, but I could indeed duplicate your bug with videos recorded with the Windows game bar.
I also agree with you that it seems to be tied directly to the VideoFileClip method.
I got my code to work by writing it like this:
full_video = VideoFileClip(input_video_path, fps_source="fps")
with the key detail being the (fps_source = "fps") bit.

play as many sounds as loop count in python

I want the alarm.play() function to repeat for the number of loops and ring 10 times as in the example, but it just keeps ringing once every time I try or change it. How can I fix this? And does it make more sense to use for instead of while ?
import time
import vlc
alarm = vlc.MediaPlayer("path")
m=0
while m<=10:
alarm.play()
time.sleep(1)
m +=1
just stop the alarm at the end of loop and befor stop it create loop for stop executing while the sound is playing
import time
import vlc
alarm = vlc.MediaPlayer("path")
m = 0
while m <= 10:
alarm.play()
time.sleep(1)
m += 1
while alarm.is_playing():
pass
alarm.stop()

Clearing NeoPixel LEDs after running animate()?

I'm trying to run an animation for a period of time, then clear the LEDs and go back to setting the colors manually with Neopixel.pixels.fill(). Only, after I run animation.animate(), I lose the ability to use pixels.fill() I tried using the sequence library with the auto_clear and auto_reset flags, but those did not seem to work either.
rainbow = Rainbow(macropad.pixels, speed = 0.005, period = 2)
animations = AnimationSequence(rainbow, auto_clear=True, auto_reset=True)
i = 0
while True:
animations.animate()
i += 1
if (i == 100):
animations.reset()
break

OBD2 Python Getting Speed

I'm having a little trouble with getting the correct speed out of my Python OBD2 reading program. It stays at 13 even if I'm not moving. I have based my code off of pi2go on git hub. Though no matter what the speed_float value is always 13 once converted from hex to a float.
def speed(self, oldValues):
""" Gets the speed of the vehicle """
if self.serialIO is None:
return "Serial IO not setup."
self.serialWrite("0D")
speed_list = self.serialRead()
if speed_list == -1 or speed_list == 0:
print("There is an issue with reading the speed of the vehicle.")
return 0
else:
speed_hex = speed_list[0]
speed_float = float(int("0x" + speed_hex, 0))
print("Speed float = " + str(speed_float))
if speedFormat == "mph":
# display speed in miles per hour
#speed_float = speed_float * 0.621371
speed_float = speed_float * 1.609 - 20.917 #made it go to zero by subtracting 20.917
print("mph = " + str(speed_float))
elif speedFormat == "kph":
# display speed in kilometers per hour
print("kph = " + str(speed_float))
return speed_float
else:
# error
print("Configuration is wrong. Please check config.py for speedFormat")
return speed_float
After I made the mph value zero it stays at zero. It never changes. The equation above that makes it something like 8.0. My issue is how do I get the actual speed.
After wasting time at work on researching this issue I was having, I found a Java open source project on git hub doing the same thing. Instead of using the first location of the list it used the second. Instead of
speed_hex = speed_list[0]
I changed it to
speed_hex = speed_list[1]
It now works correctly.

recurring notification statement after checking a condition in python

I am working on a small proof of concept and using python to illustrate the idea. The idea is the program will run in a loop and will check for input. Now if the input falls under a threshold then it sends a notification. But I am trying to restrict the notification at an interval of 4 sec. And thats where I am loosing either with the logic or with some syntax. Either way It is doing some unexpected things
1: keep on entering 0 and it will display the below threshold message until it reaches a 4 sec mark and then it just prints out the message 4 times in a single line. I want them to show after every 4 seconds. The idea is (A)the input might change in that 4 sec and the notification switches. (B)I want the notification to play out as a reminder with a recurrence of 4 sec every time the script hits the condition if weightIn < 0.5..if it is true then the notification goes out after 4 sec from the first time it was sent
Sorry if I tried over explaining it. I am pretty new to python
import threading
def main():
while True:
weightIn = float(input("Get value: "))
threshold = .5
def operation():
if weightIn < 0.5:
#send notification at an interval of 4 sec
threading.Timer(4.0, operation).start()
print("Below weight threshhold...send notification")
else:
print("You are good")
if threshold is not None:
operation()
main()
First avoid declaring functions in a loop. Then ask yourself, if an object would not be appropriate, because it properly encloses state attributes.
But for the algorithmic part, it is simple (if I have correctly understood the problem ...). Store the timestamp of last notification and send a new one if more the 4 seconds have elapsed. In pseudo-code :
last_notification_time = 0
threshold = 0.5
loop:
weighIn = get_new_value()
if weightIn < threshold:
time = get_time_in_seconds()
if (time > last_notification_time + 4):
last_notification_time = time
send_notification()
# actual processing
In Python, it could look like :
#import time
def main():
last_notification_time = 0
threshold = 0.5
while True:
weighIn = float(input("Get value: "))
if weightIn < threshold:
cur_time = time.time()
if (cur_time > last_notification_time + 4):
last_notification_time = time
print("Below weight threshhold...send notification")
# actual processing
main()

Categories

Resources