I fixed the script ... but there is no way to make my VoIP setup work properly!
Well, VoIP is a complicated thing ... but I'll try to help you. First, understand that if you have VoIP devices behind NAT/Firewall (PBX or the phone) that you will have to do some special things to make it work. You need to know that VoIP uses a SIP (signaling) port and RTP (audio) ports. The RTP connection is a separate connection unless you configure symmetric RTP. Because it is a separate connection, unless you prepare for it, you're firewall will block it and you won't hear the audio.
PBX or phones are behind NAT/Firewall. VoIP Trunk or provider is on a public IP.
Set the VoIP devices to have a keep alive of 120 seconds. This will open a connection to the VoIP Trunk and KEEP IT OPEN so that when audio comes back, the firewall will see it has a "related" connection and allow it to pass in. You'll need to look for settings in your phone or PBX for this. They are usually found under NAT menus.
PBX is behind a NAT/Firewall and phone is on another network also behind a NAT/Firewall.
You must open ports on the PBX firewall to allow connections. Port 5060 is a common one for the SIP signaling, but the RTP (audio) can come in from anywhere in the 10000-20000 range.