Spaces:
Sleeping
Sleeping
Create audio_tuner.py
Browse files- audio_tuner.py +53 -0
audio_tuner.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# audio_tuner.py
|
2 |
+
|
3 |
+
from pydub import AudioSegment
|
4 |
+
|
5 |
+
def change_audio_tuning(audio_filepath, initial_tuning_hz, desired_tuning_hz):
|
6 |
+
"""
|
7 |
+
Changes the speed of an audio file to match a desired tuning.
|
8 |
+
|
9 |
+
This function adjusts the playback speed of the audio, which in turn
|
10 |
+
changes its pitch, to move from an initial tuning to a desired tuning.
|
11 |
+
|
12 |
+
Args:
|
13 |
+
audio_filepath (str): Path to the input audio file.
|
14 |
+
initial_tuning_hz (float): The initial tuning frequency in Hz (e.g., 440).
|
15 |
+
desired_tuning_hz (float): The desired tuning frequency in Hz (e.g., 432).
|
16 |
+
|
17 |
+
Returns:
|
18 |
+
(int, numpy.ndarray): A tuple containing the new sample rate and the
|
19 |
+
audio data as a NumPy array for Gradio compatibility.
|
20 |
+
"""
|
21 |
+
# --- Input Validation ---
|
22 |
+
if not audio_filepath:
|
23 |
+
raise ValueError("No audio file provided.")
|
24 |
+
if not initial_tuning_hz or not desired_tuning_hz:
|
25 |
+
raise ValueError("Initial and desired tuning frequencies must be provided.")
|
26 |
+
if initial_tuning_hz <= 0 or desired_tuning_hz <= 0:
|
27 |
+
raise ValueError("Tuning frequencies must be positive values.")
|
28 |
+
|
29 |
+
# --- Processing ---
|
30 |
+
# Calculate the speed multiplier required to change the pitch
|
31 |
+
speed_multiplier = desired_tuning_hz / initial_tuning_hz
|
32 |
+
|
33 |
+
# Load the audio file using pydub
|
34 |
+
sound = AudioSegment.from_file(audio_filepath)
|
35 |
+
|
36 |
+
# A simple way to change speed without pitch correction is to change the frame rate
|
37 |
+
new_frame_rate = int(sound.frame_rate * speed_multiplier)
|
38 |
+
|
39 |
+
# Create a new audio segment with the modified frame rate
|
40 |
+
tuned_sound = sound._spawn(sound.raw_data, overrides={"frame_rate": new_frame_rate})
|
41 |
+
|
42 |
+
# Set the frame rate back to the original to ensure proper playback speed in most players,
|
43 |
+
# effectively resampling the audio.
|
44 |
+
tuned_sound = tuned_sound.set_frame_rate(sound.frame_rate)
|
45 |
+
|
46 |
+
# --- Output for Gradio ---
|
47 |
+
# Gradio audio component expects a tuple of (sample_rate, numpy_array)
|
48 |
+
# The sample rate is the original rate after resampling.
|
49 |
+
# The audio data is converted to a NumPy array.
|
50 |
+
import numpy as np
|
51 |
+
samples = np.array(tuned_sound.get_array_of_samples()).astype(np.int16)
|
52 |
+
|
53 |
+
return (tuned_sound.frame_rate, samples)
|