Wednesday, April 30, 2025

How to Generate CTCSS Tones - Python

Change frequency and duration to suit your needs. 

import math
import numpy as np
import pyaudio

# Define the frequency and duration of the tone
frequency = 88.5  # Hz
duration = 360  # seconds

# Generate the audio samples
samples_per_second = 44100
num_samples = samples_per_second * duration
x = np.arange(num_samples)
samples = 0.5 * np.sin(2 * np.pi * frequency * x / samples_per_second)

# Initialize PyAudio
p = pyaudio.PyAudio()

# Open a stream and play the audio
stream = p.open(format=pyaudio.paFloat32,
                channels=1,
                rate=samples_per_second,
                output=True)
stream.write(samples.astype(np.float32).tostring())

# Close the stream and PyAudio
stream.stop_stream()
stream.close()
p.terminate()

First, the necessary modules are imported:

  • math for mathematical functions
  • numpy as np for scientific computing with Python
  • pyaudio for audio input/output

The frequency and duration of the audio tone to be generated are then defined with the following lines: 

frequency = 88.5  # Hz
duration = 360  # seconds

The number of samples to generate is calculated based on the desired frequency and duration, along with the samples per second value: 

samples_per_second = 44100
num_samples = samples_per_second * duration

A numpy array x is generated to represent the time values for the audio samples to be generated: 

x = np.arange(num_samples)

The audio samples themselves are then generated as a sine wave with an amplitude of 0.5: 

samples = 0.5 * np.sin(2 * np.pi * frequency * x / samples_per_second)

PyAudio is then initialized: 

p = pyaudio.PyAudio()

An audio stream is opened with the desired format (32-bit floating point), number of channels (1), and sample rate (samples per second). The output parameter is set to True to indicate that audio should be played through the stream: 

stream = p.open(format=pyaudio.paFloat32,
                channels=1,
                rate=samples_per_second,
                output=True)

The audio samples are then written to the stream, converted to a string of 32-bit floating point values: 

stream.write(samples.astype(np.float32).tostring())

Finally, the stream is closed and PyAudio is terminated: 

stream.stop_stream()
stream.close()
p.terminate()

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...