Apps Can anyone fix this code?

I have tried to merge two apps, one that shows the drift angle and one that plays a sound on a condition. My goal is that a sound is played when certain level of drift is achieved. It is working, but the problem is that the sound sometimes is played many times, even overlapping itself. I would need a way to prevent the condition with the soundplay to be run so frequently, or maybe with some kind of timer that makes it wait for some seconds after the last time it was run. My knowledge of Python is almost zero, so I ask for your help. This is the code I have:

Code:
import sys
import ac
import acsys
import math

from math import log
from playsounddrift import playsound
from pydubdrift.pydub import AudioSegment

sound_played = False

SoundFile = "apps/python/D_Angle/hotshot.wav"

#configure
MaxAngle = 130
MinKMH = 10
Drift = 20

#label
AngleLabel = 0

#field
Angle = 0
Timer = 0

def acMain(ac_version):
    global AngleLabel

    # init Window
    appWindow = ac.newApp("D_Angle")
    ac.setSize(appWindow, 66, 30)
    ac.setTitle(appWindow, "")
    ac.drawBorder(appWindow, 0)
    ac.setIconPosition(appWindow, 0, -10000)
    ac.setBackgroundOpacity(appWindow, 0.3)

    # label configure
    AngleLabel = ac.addLabel(appWindow, "0°")
    ac.setPosition(AngleLabel, 33, 3)
    ac.setFontAlignment(AngleLabel, "center")
    ac.setFontSize(AngleLabel, 18)
    ac.setFontColor(AngleLabel, 1, 1, 1, 1)

def acUpdate(deltaT):
    global AngleLabel, Angle, Timer, MinKMH, sound_played, offset
    ac.setFontAlignment(AngleLabel, "center")
    ac.setPosition(AngleLabel, 33, 3)

    # raw data
    carKMH = ac.getCarState(0, acsys.CS.SpeedKMH)
    fl, fr, rl, rr = ac.getCarState(0, acsys.CS.SlipAngle)
    vx, vy, vz = ac.getCarState(0, acsys.CS.LocalVelocity)

    # model data
    Angle = getDriftAngle(rl, rr, vz)

    # spin : over angle
    if Angle > MaxAngle and carKMH > MinKMH:
        ac.setText(AngleLabel, "Spin")
        return

    # spin : lower speed
    if Angle > 60 and carKMH < MinKMH and vz > 0:
        ac.setText(AngleLabel, "Spin")
        return

    # drifting
    if carKMH > MinKMH:
        ac.setText(AngleLabel, "{:.0f}°".format(Angle))

    # Wait anim
    else:
        ac.setPosition(AngleLabel, 16, 3)
        Timer += deltaT
        ac.setFontAlignment(AngleLabel, "left")
        if int(Timer) % 3 == 0:
            ac.setText(AngleLabel, "Text1")
        if int(Timer) % 3 == 1:
            ac.setText(AngleLabel, "Text2")
        if int(Timer) % 3 == 2:
            ac.setText(AngleLabel, "Text3")

    if Angle > Drift and carKMH > MinKMH:
        if not sound_played:
            playsound(SoundFile, block = False)
            sound_played = True
            return
    else:
        sound_played = False
        return

def getDriftAngle(rl, rr, vz):
    rawAngle = math.fabs(round(rl+rr)/2)
    if vz <= 0:
        return 180 - rawAngle
    else:
        return rawAngle
 
Back
Top