
- SciPy - Home
- SciPy - Introduction
- SciPy - Environment Setup
- SciPy - Basic Functionality
- SciPy - Relationship with NumPy
- SciPy Clusters
- SciPy - Clusters
- SciPy - Hierarchical Clustering
- SciPy - K-means Clustering
- SciPy - Distance Metrics
- SciPy Constants
- SciPy - Constants
- SciPy - Mathematical Constants
- SciPy - Physical Constants
- SciPy - Unit Conversion
- SciPy - Astronomical Constants
- SciPy - Fourier Transforms
- SciPy - FFTpack
- SciPy - Discrete Fourier Transform (DFT)
- SciPy - Fast Fourier Transform (FFT)
- SciPy Integration Equations
- SciPy - Integrate Module
- SciPy - Single Integration
- SciPy - Double Integration
- SciPy - Triple Integration
- SciPy - Multiple Integration
- SciPy Differential Equations
- SciPy - Differential Equations
- SciPy - Integration of Stochastic Differential Equations
- SciPy - Integration of Ordinary Differential Equations
- SciPy - Discontinuous Functions
- SciPy - Oscillatory Functions
- SciPy - Partial Differential Equations
- SciPy Interpolation
- SciPy - Interpolate
- SciPy - Linear 1-D Interpolation
- SciPy - Polynomial 1-D Interpolation
- SciPy - Spline 1-D Interpolation
- SciPy - Grid Data Multi-Dimensional Interpolation
- SciPy - RBF Multi-Dimensional Interpolation
- SciPy - Polynomial & Spline Interpolation
- SciPy Curve Fitting
- SciPy - Curve Fitting
- SciPy - Linear Curve Fitting
- SciPy - Non-Linear Curve Fitting
- SciPy - Input & Output
- SciPy - Input & Output
- SciPy - Reading & Writing Files
- SciPy - Working with Different File Formats
- SciPy - Efficient Data Storage with HDF5
- SciPy - Data Serialization
- SciPy Linear Algebra
- SciPy - Linalg
- SciPy - Matrix Creation & Basic Operations
- SciPy - Matrix LU Decomposition
- SciPy - Matrix QU Decomposition
- SciPy - Singular Value Decomposition
- SciPy - Cholesky Decomposition
- SciPy - Solving Linear Systems
- SciPy - Eigenvalues & Eigenvectors
- SciPy Image Processing
- SciPy - Ndimage
- SciPy - Reading & Writing Images
- SciPy - Image Transformation
- SciPy - Filtering & Edge Detection
- SciPy - Top Hat Filters
- SciPy - Morphological Filters
- SciPy - Low Pass Filters
- SciPy - High Pass Filters
- SciPy - Bilateral Filter
- SciPy - Median Filter
- SciPy - Non - Linear Filters in Image Processing
- SciPy - High Boost Filter
- SciPy - Laplacian Filter
- SciPy - Morphological Operations
- SciPy - Image Segmentation
- SciPy - Thresholding in Image Segmentation
- SciPy - Region-Based Segmentation
- SciPy - Connected Component Labeling
- SciPy Optimize
- SciPy - Optimize
- SciPy - Special Matrices & Functions
- SciPy - Unconstrained Optimization
- SciPy - Constrained Optimization
- SciPy - Matrix Norms
- SciPy - Sparse Matrix
- SciPy - Frobenius Norm
- SciPy - Spectral Norm
- SciPy Condition Numbers
- SciPy - Condition Numbers
- SciPy - Linear Least Squares
- SciPy - Non-Linear Least Squares
- SciPy - Finding Roots of Scalar Functions
- SciPy - Finding Roots of Multivariate Functions
- SciPy - Signal Processing
- SciPy - Signal Filtering & Smoothing
- SciPy - Short-Time Fourier Transform
- SciPy - Wavelet Transform
- SciPy - Continuous Wavelet Transform
- SciPy - Discrete Wavelet Transform
- SciPy - Wavelet Packet Transform
- SciPy - Multi-Resolution Analysis
- SciPy - Stationary Wavelet Transform
- SciPy - Statistical Functions
- SciPy - Stats
- SciPy - Descriptive Statistics
- SciPy - Continuous Probability Distributions
- SciPy - Discrete Probability Distributions
- SciPy - Statistical Tests & Inference
- SciPy - Generating Random Samples
- SciPy - Kaplan-Meier Estimator Survival Analysis
- SciPy - Cox Proportional Hazards Model Survival Analysis
- SciPy Spatial Data
- SciPy - Spatial
- SciPy - Special Functions
- SciPy - Special Package
- SciPy Advanced Topics
- SciPy - CSGraph
- SciPy - ODR
- SciPy Useful Resources
- SciPy - Reference
- SciPy - Quick Guide
- SciPy - Cheatsheet
- SciPy - Useful Resources
- SciPy - Discussion
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!