Plotting Various Sounds on Graphs using Python and Matplotlib


In the world of audio processing and analysis, visualizing sound waveforms can provide valuable insights, Python, a popular programming language, combined with the powerful plotting library Matplotlib, offers a versatile platform for plotting and analyzing different types of sounds.

In this article, we explore how to generate and plot waveforms for various sounds, such as sine waves, square waves, sawtooth waves, and noise signals. By leveraging Python and Matplotlib, we can visualize sound data and gain a deeper understanding of their characteristics and patterns.

How to plot various Sounds on Graphs using Python and Matplotlib?

Follow the steps given below to plot various Sounds on Graphs using Python and Matplotlib −

  • We start by importing the necessary libraries: NumPy and Matplotlib. NumPy is a library for numerical operations in Python, and Matplotlib is a plotting library that we will use to visualize the sound waveforms.

  • Next, we define a function called plot_sound(sound, sample_rate) that takes two parameters: sound (the sound array) and sample_rate (the sample rate of the sound). This function will plot the sound waveform.

  • Inside the plot_sound function, we first calculate the duration of the sound by dividing the length of the sound array by the sample rate. This gives us the total duration of the sound in seconds.

  • We then create a time axis using the linspace function from NumPy. The linspace function generates evenly spaced numbers over a specified range. In this case, we create a time axis that ranges from 0 to the duration of the sound, with the same number of points as the length of the sound array.

  • Now, we can plot the sound waveform using Matplotlib. We use the plot function from Matplotlib to plot the time axis on the x-axis and the sound array on the y-axis.

  • We add labels to the x-axis and y-axis using the xlabel and ylabel functions, respectively.

  • We set a title for the plot using the title function.

  • We enable the grid on the plot using the grid function.

  • Finally, we display the plot using the show function.

  • After defining the plot_sound function, we proceed to demonstrate its usage by generating four different types of sounds and plotting their waveforms.

  • We first set the sample rate and duration of the sounds.

  • In the program below, we generate a sine wave using the sin function from NumPy. The sin function generates a sine wave based on the specified frequency and time array.

  • We generate a square wave by applying the sign function to the sine wave. The sign function returns -1 for negative values and 1 for positive values, effectively converting the sine wave into a square wave.

  • We generate a sawtooth wave by using the modulo operator to wrap the values of a linearly spaced array between -1 and 1. This creates a sawtooth-like waveform.

  • We generate a noise signal by sampling random values from a uniform distribution between -1 and 1.

  • Finally, we call the plot_sound function for each of the generated sounds to plot their waveforms.

Example

Below is the program suing the above steps −

import numpy as np
import matplotlib.pyplot as plt

def plot_sound(sound, sample_rate):
   duration = len(sound) / sample_rate
   time = np.linspace(0, duration, len(sound))
    
   plt.plot(time, sound)
   plt.xlabel("Time (seconds)")
   plt.ylabel("Amplitude")
   plt.title("Sound Waveform")
   plt.grid(True)
   plt.show()

# Example usage
sample_rate = 44100  # Sample rate of the sound
duration = 2  # Duration of the sound in seconds

# Generate a sine wave
frequency = 440  # Frequency of the sine wave in Hz
t = np.linspace(0, duration, int(sample_rate * duration))
sine_wave = np.sin(2 * np.pi * frequency * t)

# Generate a square wave
square_wave = np.sign(np.sin(2 * np.pi * frequency * t))

# Generate a sawtooth wave
sawtooth_wave = np.linspace(-1, 1, int(sample_rate * duration)) % 2 - 1

# Generate a noise signal
noise = np.random.uniform(-1, 1, int(sample_rate * duration))

# Plotting the sound waveforms
plot_sound(sine_wave, sample_rate)
plot_sound(square_wave, sample_rate)
plot_sound(sawtooth_wave, sample_rate)
plot_sound(noise, sample_rate)

Output

In the above program, we then demonstrated the usage of the plot_sound function by generating and plotting four different types of sounds −

  • A sine wave with a frequency of 440 Hz.

  • A square wave with the same frequency.

  • A sawtooth wave with the same frequency.

  • A random noise signal.

Each sound is generated using NumPy functions, and the resulting waveforms are plotted using the plot_sound function.

Conclusion

Through the utilization of Python and Matplotlib, we have showcased the capacity to create and depict diverse sound wave patterns. The amalgamation of Python's adaptable nature and Matplotlib's visualization capabilities empowers us to examine and comprehend various sound attributes, including fluctuations in frequency and amplitude.

This acquired knowledge holds great value in domains like audio processing, music production, and sound engineering, presenting endless opportunities for further investigation and experimentation.

Updated on: 25-Jul-2023

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements