Python Soundfile Examples
Python Soundfile: How To Examples
The Python Soundfile library provides a simple way to read and write sound files in various formats. It is built on top of the libsndfile library and supports several common audio file formats such as WAV, FLAC, and OGG Vorbis.
In this tutorial, we will go through several examples to demonstrate the usage of the Python Soundfile library.
Example 1: Reading a Sound File
To read a sound file using the Soundfile library, you can use the read() function. This function takes the file path as input and returns two values: the audio data and the sample rate.
import soundfile as sf
# Read a sound file
data, samplerate = sf.read('audio.wav')
print(data) # Audio data as a numpy array
print(samplerate) # Sample rate of the audio file
Expected output:
data: A numpy array containing the audio data.samplerate: The sample rate of the audio file.
Example 2: Writing a Sound File
To write audio data to a sound file, you can use the write() function. This function takes the file path, audio data, and sample rate as input.
import soundfile as sf
import numpy as np
# Generate some audio data
data = np.random.uniform(-1, 1, 44100) # 1 second of random audio
samplerate = 44100
# Write the audio data to a sound file
sf.write('output.wav', data, samplerate)
Expected output:
- A sound file named "output.wav" containing the generated audio data.
Example 3: Changing the Sample Rate
The Soundfile library allows you to change the sample rate of an audio file using the convert() function. This function takes the audio data, target sample rate, and the output file path as input.
import soundfile as sf
# Read a sound file
data, samplerate = sf.read('audio.wav')
# Convert the sample rate to 22050
target_samplerate = 22050
converted_data = sf.convert(data, target_samplerate)
# Write the converted audio to a new file
sf.write('converted.wav', converted_data, target_samplerate)
Expected output:
- A sound file named "converted.wav" with the same audio content as the input file but with a sample rate of 22050.
Example 4: Extracting a Portion of Audio
You can extract a portion of audio from a sound file using the Soundfile library. The extract_sub_audio() function below demonstrates how to extract a specified segment of audio from a sound file.
import soundfile as sf
def extract_sub_audio(input_file, output_file, start_time, end_time):
# Read the input sound file
data, samplerate = sf.read(input_file)
# Calculate the start and end sample indices
start_sample = int(start_time * samplerate)
end_sample = int(end_time * samplerate)
# Extract the sub-audio
sub_audio = data[start_sample:end_sample]
# Write the sub-audio to a new file
sf.write(output_file, sub_audio, samplerate)
# Example usage: extracting 10 seconds of audio starting from 5 seconds
extract_sub_audio('audio.wav', 'sub_audio.wav', 5, 15)
Expected output:
- A sound file named "sub_audio.wav" containing the extracted 10-second portion of audio starting from the 5th second.
Example 5: Adding Fade-in and Fade-out Effects
You can apply fade-in and fade-out effects to an audio file using the Soundfile library. The apply_fade_effects() function below demonstrates how to add fade-in and fade-out effects to an audio file.
import soundfile as sf
import numpy as np
def apply_fade_effects(input_file, output_file, fade_in_duration, fade_out_duration):
# Read the input sound file
data, samplerate = sf.read(input_file)
# Calculate the fade-in and fade-out sample counts
fade_in_samples = int(fade_in_duration * samplerate)
fade_out_samples = int(fade_out_duration * samplerate)
# Apply the fade-in effect
fade_in_curve = np.linspace(0, 1, fade_in_samples)
data[:fade_in_samples] *= fade_in_curve[:, np.newaxis]
# Apply the fade-out effect
fade_out_curve = np.linspace(1, 0, fade_out_samples)
data[-fade_out_samples:] *= fade_out_curve[:, np.newaxis]
# Write the modified audio to a new file
sf.write(output_file, data, samplerate)
# Example usage: applying a fade-in effect of 2 seconds and a fade-out effect of 1 second
apply_fade_effects('audio.wav', 'fade_effects.wav', 2, 1)
Expected output:
- A sound file named "fade_effects.wav" with fade-in and fade-out effects applied to the audio content.
Example 6: Normalizing the Audio
You can normalize the audio levels of a sound file using the Soundfile library. The normalize_audio() function below demonstrates how to normalize the audio levels to a specified maximum value.
import soundfile as sf
import numpy as np
def normalize_audio(input_file, output_file, target_max):
# Read the input sound file
data, samplerate = sf.read(input_file)
# Calculate the maximum value of the audio data
max_value = np.max(np.abs(data))
# Normalize the audio data
normalized_data = data * (target_max / max_value)
# Write the normalized audio to a new file
sf.write(output_file, normalized_data, samplerate)
# Example usage: normalizing the audio levels to a maximum value of 0.5
normalize_audio('audio.wav', 'normalized.wav', 0.5)
Expected output:
- A sound file named "normalized.wav" with the audio levels normalized to a maximum value of 0.5.
Example 7: Resampling the Audio
The Soundfile library allows you to resample the audio to a different sample rate using the resample() function. The example below demonstrates how to resample an audio file to a target sample rate.
import soundfile as sf
# Read a sound file
data, samplerate = sf.read('audio.wav')
# Resample the audio to a sample rate of 44100
target_samplerate = 44100
resampled_data = sf.resample(data, target_samplerate)
# Write the resampled audio to a new file
sf.write('resampled.wav', resampled_data, target_samplerate)
Expected output:
- A sound file named "resampled.wav" with the audio resampled to a sample rate of 44100.
Example 8: Getting the Duration of an Audio File
To get the duration of an audio file using the Soundfile library, you can divide the length of the audio data by the sample rate. The example below demonstrates how to calculate the duration of an audio file.
import soundfile as sf
# Read a sound file
data, samplerate = sf.read('audio.wav')
# Calculate the duration in seconds
duration = len(data) / samplerate
print(duration) # Duration of the audio file in seconds
Expected output:
- The duration of the audio file in seconds.
Example 9: Splitting a Stereo Audio File
You can split a stereo audio file into two mono audio files using the Soundfile library. The split_stereo_audio() function below demonstrates how to split a stereo audio file into two separate mono audio files.
import soundfile as sf
def split_stereo_audio(input_file, output_file_left, output_file_right):
# Read the input sound file
data, samplerate = sf.read(input_file)
# Split the stereo audio into two mono channels
left_channel = data[:, 0]
right_channel = data[:, 1]
# Write the left and right channels to separate files
sf.write(output_file_left, left_channel, samplerate)
sf.write(output_file_right, right_channel, samplerate)
# Example usage: splitting a stereo audio file into two mono files
split_stereo_audio('stereo.wav', 'left.wav', 'right.wav')
Expected output:
- Two sound files named "left.wav" and "right.wav", containing the left and right channels of the stereo audio file, respectively.
Example 10: Concatenating Audio Files
You can concatenate multiple audio files into a single audio file using the Soundfile library. The concatenate_audio_files() function below demonstrates how to concatenate two audio files.
import soundfile as sf
import numpy as np
def concatenate_audio_files(input_files, output_file):
# Initialize an empty list to store the audio data
audio_data = []
# Read each input sound file and append the audio data
for file in input_files:
data, _ = sf.read(file)
audio_data.append(data)
# Concatenate the audio data along the time axis
concatenated_data = np.concatenate(audio_data)
# Write the concatenated audio to a new file
sf.write(output_file, concatenated_data, len(concatenated_data))
# Example usage: concatenating two audio files into a single file
concatenate_audio_files(['audio1.wav', 'audio2.wav'], 'concatenated.wav')
Expected output:
- A sound file named "concatenated.wav" containing the concatenated audio data from the input files.
These examples demonstrate some of the common tasks you can perform using the Python Soundfile library. You can explore the library further to discover more functionalities and options it provides for working with sound files.