SciPy - write() Function



The scipy.io.wavfile.write() function turns audio data into .wav files. The .wav format is a basic audio file type that works on most platforms and devices. The function allows you to alter raw audio data into a file you can play.

This function is useful for developers and researchers to work on audio signal processing. With this method, you can compose sound effects, save computer-synthesized audio, and export processed audio data, for instance, in some multimedia project. You may be making a test signal, music, or audio for machine learning; with this function you will be able to record your audio data fast.

Errors may occur while using .wav file such as if audio files do not have the correct format. For example, when you're dealing with floating-point numbers that aren't normalized or have values outside of the [-1.0, 1.0] range or if you are utilizing a sample rate that's not an integer.

You may also find difficulties with file paths. File paths may not be located or may lack appropriate permissions. To solve most of these problems check that your data has the correct format, your file paths are valid, and you're using appropriate sample rates.

Syntax

The syntax for the Scipy method is as follows −

.wavfile.write(filename, rate, data)

Parameters

This method accepts the following parameters −

  • filename − File path or file-like object to save the .wav file.

  • rate − The sample rate (e.g., 44100 for standard audio).

  • data − The audio data, as an array of integers or normalized floating-point numbers.

Return Value

The scipy.io.wavfile.write method does not return any value. Its purpose is to save the provided audio data to the specified file, and it performs this task silently without producing a return value.

Example 1: Creating a Basic Sine Wave Audio File

This is an example of using scipy.io.wavfile.write to generate and save a pure sine wave audio file. The file generated is simply a tone of 440 Hz (often called the musical note A4), lasting 2 seconds.

This is the code, creating time array and calculating the values of sine wave with any frequency. The resultant saved values are as a.wav file, which could easily be listened back using any player.

import numpy as np
from scipy.io.wavfile import write

rate = 44100
duration = 2
frequency = 440
t = np.linspace(0, duration, int(rate * duration), endpoint=False)
data = (0.5 * np.sin(2 * np.pi * frequency * t)).astype(np.float32)
write("sine_wave.wav", rate, data)

print("Audio file 'sine_wave.wav' has been successfully created.")

When we run above program, it produces following result −

Audio file 'sine_wave.wav' has been successfully created.

Example 2

This example demonstrates how to build a stereo audio file with various frequencies played on each channel. A 440 Hz tone is played on the left, while an 880 Hz tone is produced on the right.

The code records the audio by generating separate sine waves for the left and right channels and combining them into a 2D array. The output file comprises two separate tones played simultaneously through various speakers or channels.

import numpy as np
from scipy.io.wavfile import write

rate = 44100
duration = 2
freq_left = 440
freq_right = 880
t = np.linspace(0, duration, int(rate * duration), endpoint=False)
left_channel = (0.5 * np.sin(2 * np.pi * freq_left * t)).astype(np.float32)
right_channel = (0.5 * np.sin(2 * np.pi * freq_right * t)).astype(np.float32)
stereo_data = np.column_stack((left_channel, right_channel))
write("stereo_audio.wav", rate, stereo_data)

print("stereo_audio.wav' created successfully.")

Following is an output of the above code −

stereo_audio.wav created successfully.

Example 3: Writing Integer Audio Data

The below example, saves the sine wave as integer audio data, which is the most common format for .wav files. Integer data is compatible with almost all of the audio devices and players.

The sine wave is scaled to be within the integer range and formatted as int16 before saving. The resulting .wav file produces a sharp 440 Hz tone and shows how integer data can be used in audio files.

import numpy as np
from scipy.io.wavfile import write

rate = 44100
duration = 2
frequency = 440
t = np.linspace(0, duration, int(rate * duration), endpoint=False)
data = (32767 * np.sin(2 * np.pi * frequency * t)).astype(np.int16)
write("integer_audio.wav", rate, data)

print("'integer_audio.wav' created successfully.")

Output of the above code is as follows −

'integer_audio.wav' created successfully.

Example 4: Normalized Floating-Point Audio

This examples shows how one can save a sine wave using normalized floating-point data, that is, the audio values are in the range -1.0 to 1.0. It is handy for dealing with raw or unscaled audio signals.

The below code, is creating and normalizing the sine wave before writing it to the file. Output .wav contains a smooth 440 Hz tone keeping data within the desired range.

import numpy as np
from scipy.io.wavfile import write

rate = 44100
duration = 1
frequency = 440
t = np.linspace(0, duration, int(rate * duration), endpoint=False)
data = np.sin(2 * np.pi * frequency * t).astype(np.float32)
write("normalized_audio.wav", rate, data)

print(f"'normalized_audio.wav' created successfully.")

Output of the above code is as follows −

'normalized_audio.wav' created successfully.

Example 5: Writing Noisy Audio

This example produces a noisy audio file by adding random white noise to a sine wave. It shows how to create a noisy environment for testing audio processing algorithms.

In the below code, white noise is generated and added to the sine wave signal. The produced file has a 440 Hz tone contained in noise that can be used for audio filtering or noise reduction studies.

import numpy as np
from scipy.io.wavfile import write

rate = 44100
duration = 2
frequency = 440
t = np.linspace(0, duration, int(rate * duration), endpoint=False)
sine_wave = (0.5 * np.sin(2 * np.pi * frequency * t)).astype(np.float32)
noise = np.random.normal(0, 0.1, sine_wave.shape).astype(np.float32)
data = sine_wave + noise
write("noisy_audio.wav", rate, data)

print("'noisy_audio.wav' created successfully.")

Output of the above code is as follows −

'noisy_audio.wav' created successfully.

Example 6: Unsupported Data Types in .wav file

Attribute error occurs when data is not of one of the allowed data types, like normalized floating point numbers (float32 between -1.0 and 1.0), or integers (int16, int32).

In the below code we have created a .wav file using scipy.io.write() method with the incorrect data type to check the Attribute error. Following is the code −

import numpy as np
from scipy.io.wavfile import write

rate = 44100  # Sample rate (Hz)
duration = 2  # seconds
freq = 440.0  # Frequency of the sine wave (Hz)

# Generate a 2-second sine wave with 16-bit PCM format
t = np.linspace(0, duration, int(rate * duration), endpoint=False)
data = (np.sin(2 * np.pi * freq * t) * 32767).astype(np.int16)  # Convert to int16

write("example.wav", rate, data)  # Save as WAV file
print("WAV file 'example.wav' saved successfully!")

Output of the above code is as follows −

WAV file 'example.wav' saved successfully!
scipy_input_output.htm
Advertisements