import os
import time
import math
import numpy as np
from scipy.io.wavfile import write


def generate_sound(duration: float, frequency_start: float, frequency_end: float, sample_rate: int = 44100,
                   amplitude: float = 0.3, output_file: str = "output.wav"):
    """
    Generates a sound with a frequency that adjusts slowly and increments, and plays it on the speakers of a Mac computer.

    Parameters:
    - duration: float
        The duration of the sound in seconds.
    - frequency_start: float
        The starting frequency of the sound.
    - frequency_end: float
        The ending frequency of the sound.
    - sample_rate: int (optional)
        The sample rate of the sound. Default is 44100.
    - amplitude: float (optional)
        The amplitude of the sound. Default is 0.3.
    - output_file: str (optional)
        The name of the output file to save the sound as a WAV file. Default is "output.wav".

    Returns:
    - None

    Raises:
    - ValueError:
        Will raise an error if the duration, frequency_start, or frequency_end is not a positive number.
    """

    # Validating the input parameters
    if duration <= 0:
        raise ValueError("Duration should be a positive number.")
    if frequency_start <= 0:
        raise ValueError("Starting frequency should be a positive number.")
    if frequency_end <= 0:
        raise ValueError("Ending frequency should be a positive number.")

    # Calculate the number of samples
    num_samples = int(duration * sample_rate)

    # Calculate the time array
    t = np.linspace(0, duration, num_samples, endpoint=False)

    # Calculate the frequency array
    #xRange = np.linspace(0,1,num_samples, endpoint=True)
    frequency_array = np.linspace(frequency_start, frequency_end, num_samples, endpoint=False)
    #frequency_array = 500 * np.sqrt( abs(xRange)) + 50
    #frequency_array = 200 * (xRange**4) + 100
    #frequency_array = 200 * xRange + 100
    #print(len(frequency_array))
    # Generate the sound wave
    sound_wave = amplitude * np.sin(2 * np.pi * frequency_array * t)

    # Convert the sound wave to 16-bit integers
    sound_wave_int = np.int16(sound_wave * 32767)

    # Save the sound wave as a WAV file
    write(output_file, sample_rate, sound_wave_int)



# Example usage of the generate_sound function
duration = 10.0
frequency_start = 440.0
frequency_end = 880.0
sample_rate = 44100
amplitude = 0.3
output_file = "E:\PythonMedia\sound\output3.wav"

try:
    generate_sound(duration, frequency_start, frequency_end, sample_rate, amplitude, output_file)
except ValueError as e:
    print(f"Error generating sound: {e}")

By Admin

Think-Math Website