Need help with a looping weapon sound (I want the sound to end when keydown(IN_ATTACK) is false

Hello everyone. I have been encountering problems with a script I am making for my PPSH-41. Basically, it’s primary firing sound is a loop. I want this loop to stop when Keydown(IN_ATTACK) is false (when I take my finger off mouse1). After that sound is stopped, I want another sound to play after it.

Here’s my current code (the looping sound is only stopping when magcount is 0):

if not sound_int then
gun = CreateSound( self.Owner, “weapons/loop/ostfrontppsh20.wav” )
sound_int = true
end

if self.Owner:KeyDown(IN_ATTACK) and self.Weapon:Clip1() > 0 and !self.dt.Running and !self.Owner:KeyDown(IN_USE) then
	gun:Play()
	sound_end = true
else 
	gun:Stop()
	if not self.Owner:KeyDown(IN_ATTACK) and sound_end then
		self.Owner:EmitSound(Sound("weapons/loop/cue22.wav"))
		sound_end = false
	end

end

By the way, this script is for the SWEP:PrimaryAttack Function.


// SWEP:Init
if not IsValid( self.gunsound ) then
	self.gunsound = CreateSound( self.Owner, "weapons/loop/ostfrontppsh20.wav" )
end
if not IsValid( self.gunsound2 ) then
	self.gunsound2 = CreateSound( self.Owner, "weapons/loop/cue22.wav" )
end

// SWEP:Think
if self.Owner:KeyDown(IN_ATTACK) and self.Weapon:Clip1() > 0 and !self.dt.Running and !self.Owner:KeyDown(IN_USE) then
	self.gunsound:Play()
	self.gunsound2:Stop()
elseif (!self.Owner:KeyDown(IN_ATTACK) || self.Weapon:Clip1() <= 0 ) then
	self.gunsound:Stop()
	self.gunsound2:Play()
end


Untested, but should be something along these lines.

Use


 tags to highlight code.

hmmm… it doesn’t work. the looping sound is playing forever, and it occasionally is crashing my game.

Where are you using this

[lua]if not IsValid( self.gunsound ) then
self.gunsound = CreateSound( self.Owner, “weapons/loop/ostfrontppsh20.wav” )
end
if not IsValid( self.gunsound2 ) then
self.gunsound2 = CreateSound( self.Owner, “weapons/loop/cue22.wav” )
end[/lua]

Because seems like you’re running this inside PrimmaryAttack or think

i’m using it in swep:initialize, currently, but I did add local statements in swep:think, just so it knows what gunsound and gunsound2 is.

Post your code, it sounds like you may being doing something wrong.

I basically put robotboy655’s //SWEP:Init Code into function SWEP:Initialize section of my weapon base, and I of course put the //SWEP:Think Code into the function SWEP:think section of my weapon base. if you want, I can give you a link to my current code, but I can as well describe what I’m doing thoroughly.