python – I am trying to find the frequency of an audio file and then output to a specific target frequency
I am trying to find the frequency of an audio file and then output to a specific target frequency without distorting audio, playback speed and length of song.
This is the code I am using to detect the signal of an audio files frequency:
from scipy.fftpack import fft, fftfreq
import numpy as np
from scipy.io import wavfile
import os
def frequency_spectrum(x, sf):
"""
Derive frequency spectrum of a signal from time domain
:param x: signal in the time domain
:param sf: sampling frequency
:returns frequencies and their content distribution
"""
x = x - np.average(x) # zero-centering
n = len(x)
k = np.arange(n)
tarr = n / float(sf)
frqarr = k / float(tarr) # two sides frequency range
frqarr = frqarr[:n // 2] # one side frequency range
x = fft(x) / n # fft computing and normalization
x = x[:n // 2]
return frqarr, abs(x)
def tune_to_frequency(audio_file, target_frequency):
# Read the audio file
sr, signal = wavfile.read(audio_file)
y = signal[:, 0] # use the first channel (or take their average, alternatively)
t = np.arange(len(y)) / float(sr)
# Calculate FFT and frequency spectrum
frq, X = frequency_spectrum(y, sr)
# Find the closest frequency bin to the target frequency
Read more here: Source link
