Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

distortion audio #285

Open
BillyBSig opened this issue Nov 7, 2024 · 0 comments
Open

distortion audio #285

BillyBSig opened this issue Nov 7, 2024 · 0 comments

Comments

@BillyBSig
Copy link

Hi, I'm trying to use PyVoIP version 1.6.8 and FreePBX with both alaw and ulaw codecs enabled.

I'm attempting to record incoming audio with the Python code below, but the saved audio output is distorted and messy. The recorded byte output looks like this:

b'\x80\x80\x80\x80\x80\x80\x80\x80\x80\x7f\x80\x80\x80\x80\x80\x80\x80\x80\x80\x7f'
b'\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x80\x80\x80\x80'
b'\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x80\x80\x80\x80\x80\x80'
b'\x83\x84\x83\x83\x83\x83\x83\x82\x81\x81\x82\x80~\x7f\x7f~}}~|'
b'{xz{zz|||}}\x7f\x7f\x80\x81\x82\x83\x83\x86\x86'
b'yz{z{}}}~\x80\x80\x81\x83\x83\x84\x84\x84\x84\x84\x84'
b'\x7f~~}}||{|{|||}}~~\x7f\x80\x80'

there is only distortion sound on the saved audio.

Can anyone help me with this?

Thanks

from pyVoIP.VoIP import VoIPPhone, CallState
import time
import logging
import os
import wave

# Set up logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

def convert_to_wav(audio_buffer, filename):
    """
    Convert audio buffer to WAV format using the wave module
    """
    try:
        # Join all audio chunks
        audio_data = b"".join(audio_buffer)
        
        # Open WAV file for writing
        with wave.open(filename, 'wb') as wav_file:
            wav_file.setnchannels(1)  # Mono
            wav_file.setsampwidth(2)  # 16-bit audio
            wav_file.setframerate(8000)  # 8kHz sampling rate
            
            if len(audio_data) % 2 != 0:
                audio_data = audio_data[:-1]  # Ensure even length
            
            wav_file.writeframes(audio_data)
        
        logging.info(f"Audio saved successfully to {filename}")
        return True
    except Exception as e:
        logging.error(f"Error converting audio to WAV: {str(e)}")
        return False



def answer(call):
    """
    Handle incoming calls and record audio
    """
    tmp_dir = os.path.join(os.getcwd(), "recordings")
    os.makedirs(tmp_dir, exist_ok=True)
    filename = f"audio_{int(time.time())}.wav"
    tmp_filename = os.path.join(tmp_dir, filename)
    buffer = []
    total_samples = 0
    
    try:
        call.answer()
        logging.info(f"Call answered from {call.call_id}")
        # Process audio while call is active
        while call.state == CallState.ANSWERED:
            
            try:
                audio = call.read_audio(length=160, blocking=True)
                if audio:
                    print(audio[:20])
                    buffer.append(audio)
                    total_samples += len(audio)
                    if total_samples >= 40000:
                        if convert_to_wav(buffer, tmp_filename):
                            print(f"Saved audio chunk to {filename}")
                            buffer = []
                            total_samples = 0
                            # Create new filename for next chunk
                            tmp_filename = os.path.join(tmp_dir,  f"audio_{int(time.time())}.wav")
            except Exception as e:
                logging.error(f"Error reading audio: {str(e)}")
                break
                
        # Save any remaining audio in buffer
        if buffer:
            convert_to_wav(buffer, tmp_filename)
            
    except Exception as e:
        logging.error(f"Error during call: {str(e)}")
    finally:
        try:
            call.hangup()
            logging.info("Call ended")
        except:
            pass

def main():
    # VoIP configuration
    sip_config = {
        'server': 'ip server',
        'port': 5060,
        'username': "1001",
        'password': "password",
        'local_ip': "local ip",
        'rtp_port_low': 10000,
        'rtp_port_high': 20000
    }
    
    try:
        # Initialize VoIP client
        client = VoIPPhone(
            sip_config['server'],
            sip_config['port'],
            sip_config['username'],
            sip_config['password'],
            callCallback=answer,
            myIP=sip_config['local_ip'],
            sipPort=sip_config['port'],
            rtpPortLow=sip_config['rtp_port_low'],
            rtpPortHigh=sip_config['rtp_port_high']
        )
        
        # Start client
        client.start()
        logging.info("VoIP client started. Press Ctrl+C to stop...")
        
        # Keep running until interrupted
        try:
            while True:
                pass
        except KeyboardInterrupt:
            logging.info("Shutting down...")
            
    except Exception as e:
        logging.error(f"Error starting VoIP client: {str(e)}")
    finally:
        client.stop()
        logging.info("VoIP client stopped")

if __name__ == "__main__":
    main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant