0% found this document useful (0 votes)
5 views3 pages

Assignment 1 Rajveer Saini: Question 2 Code

The document contains an assignment by Rajveer Saini that involves audio signal processing using Python. It includes code for generating sine waves, performing Fast Fourier Transform (FFT) on audio files, and plotting frequency spectra and spectrograms for musical notes. The results section summarizes the dominant frequencies detected and the ratio of dominant frequencies between two notes.

Uploaded by

Rajveer Saini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Assignment 1 Rajveer Saini: Question 2 Code

The document contains an assignment by Rajveer Saini that involves audio signal processing using Python. It includes code for generating sine waves, performing Fast Fourier Transform (FFT) on audio files, and plotting frequency spectra and spectrograms for musical notes. The results section summarizes the dominant frequencies detected and the ratio of dominant frequencies between two notes.

Uploaded by

Rajveer Saini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

MCL 314

ASSIGNMENT 1
Rajveer Saini

Question 1

A) pip install sounddevice


import sounddevice as sd
import numpy as np
x = np.linspace(0,10,300000)
f = 500
y = np.sin(2 * np.pi * f * x)
sd.play(y,samplerate=48000)

B) x = np.linspace(0,5,200000)
f1= 500
f2= 501
y = np.sin(2 * np.pi * f1 * x) + np.sin(2 * np.pi * f2 * x)
sd.play(y,samplerate=48000)

Question 2 Code and Results

Question 2 Code

!pip install scipy


import scipy.io.wavfile as wavfile # Import module for handling WAV audio files
from scipy.fft import fft, fftfreq # Import FFT functions for frequency analysis
import numpy as np
import matplotlib.pyplot as plt

# Function to load an audio file and return its sample rate and signal
def load_audio(file_path):
sample_rate, data = wavfile.read(file_path) # Read WAV file
if data.ndim > 1: # Convert stereo to mono if necessary
data = data.mean(axis=1)
return sample_rate, data

# Function to perform FFT and identify the dominant frequency in the signal
def find_dominant_frequency(signal, sample_rate):
n = len(signal) # Get the number of samples
yf = fft(signal) # Compute the Fast Fourier Transform (FFT)
xf = fftfreq(n, 1 / sample_rate) # Compute frequency bins

# Consider only positive frequencies (FFT is symmetric)


positive_freq = xf[:n // 2]
magnitude = np.abs(yf[:n // 2])

# Find the dominant frequency (highest magnitude)


dominant_freq = positive_freq[np.argmax(magnitude)]
return dominant_freq, positive_freq, magnitude

# Function to generate and display a spectrogram of the signal


def plot_spectrogram(signal, sample_rate, title):
plt.figure(figsize=(10, 4))
plt.specgram(signal, Fs=sample_rate, NFFT=1024, cmap='viridis')
plt.title(f'Spectrogram of {title}')
plt.xlabel('Time (s)')
plt.ylabel('Frequency (Hz)')
plt.colorbar(label='Intensity (dB)')
plt.show()

# List of musical notes and their corresponding file paths


notes = ["C4", "D4", "E4", "F4", "G4", "A4", "B4", "C5"]
file_paths = [f"{note}.wav" for note in notes] # List of WAV file names

# Dictionary to store dominant frequencies for each note


dominant_frequencies = {}
# Process each note and analyze its frequency properties
for note, file_path in zip(notes, file_paths):
sample_rate, signal = load_audio(file_path) # Load audio file

# Compute dominant frequency and frequency spectrum


dominant_freq, positive_freq, magnitude = find_dominant_frequency(signal, sample_rate)
dominant_frequencies[note] = dominant_freq # Store the result

# Plot frequency spectrum


plt.figure(figsize=(10, 4))
plt.plot(positive_freq, magnitude)
plt.title(f'Frequency Spectrum of {note}')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.show()

# Plot the spectrogram of the note


plot_spectrogram(signal, sample_rate, note)

# Display the dominant frequencies detected


print("Dominant Frequencies:")
for note, freq in dominant_frequencies.items():
print(f"{note}: {freq:.2f} Hz")

# Compute the ratio of dominant frequencies between C5 and C4


c4_freq = dominant_frequencies["C4"]
c5_freq = dominant_frequencies["C5"]
ratio = c5_freq / c4_freq
print(f"\nRatio of dominant frequency of C5 to C4: {ratio:.2f}")

Question 2 Results

Below are the results from the analysis, including frequency spectra and spectrograms.

You might also like