WAV files store sound data. Handling them lets you read, analyze, and save audio in your programs.
WAV audio file handling in SciPy
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
SciPy
from scipy.io import wavfile # Read a WAV file sample_rate, data = wavfile.read('filename.wav') # Write data to a WAV file wavfile.write('output.wav', sample_rate, data)
sample_rate is how many samples per second the audio has.
data is a NumPy array with the sound values.
Examples
SciPy
from scipy.io import wavfile sample_rate, data = wavfile.read('sound.wav')
SciPy
wavfile.write('new_sound.wav', sample_rate, data)SciPy
print(f'Sample rate: {sample_rate} Hz') print(f'Data shape: {data.shape}')
Sample Program
This program reads a WAV file, prints its sample rate, data type, shape, and duration. It also normalizes the audio data if it is stored as integers.
SciPy
from scipy.io import wavfile import numpy as np # Read WAV file sample_rate, data = wavfile.read('example.wav') # Print basic info print(f'Sample rate: {sample_rate} Hz') print(f'Data type: {data.dtype}') print(f'Data shape: {data.shape}') # Calculate duration in seconds duration = data.shape[0] / sample_rate print(f'Duration: {duration:.2f} seconds') # Normalize audio data to range -1 to 1 if integer type if np.issubdtype(data.dtype, np.integer): max_val = np.iinfo(data.dtype).max min_val = np.iinfo(data.dtype).min data_norm = data.astype(np.float32) data_norm[data_norm < 0] /= -min_val data_norm[data_norm >= 0] /= max_val print(f'First 5 normalized samples: {data_norm[:5]}') else: print('Data is not integer type, skipping normalization.')
Important Notes
WAV files can have one (mono) or two (stereo) channels. The data shape changes accordingly.
Normalization helps when you want to process audio values between -1 and 1.
Make sure the WAV file exists in your working folder or provide the full path.
Summary
Use scipy.io.wavfile.read to load WAV audio into arrays.
Use scipy.io.wavfile.write to save arrays back to WAV files.
Check sample rate and data shape to understand your audio file.
Practice
1. What does the function
scipy.io.wavfile.read return when you load a WAV audio file?easy
Solution
Step 1: Understand the function purpose
scipy.io.wavfile.readis designed to load WAV files and extract audio information.Step 2: Identify the returned values
It returns two things: the sample rate (how many samples per second) and the audio data as a NumPy array.Final Answer:
The sample rate and the audio data as a NumPy array -> Option CQuick Check:
read() returns (rate, data) [OK]
Hint: Remember read() gives rate and data array [OK]
Common Mistakes:
- Thinking it returns only audio data
- Confusing sample rate with file size
- Expecting metadata like format or bit depth
2. Which of the following is the correct way to import the WAV file reading function from scipy?
easy
Solution
Step 1: Recall correct import syntax
Python imports use 'from module import function_or_submodule' format.Step 2: Match with scipy structure
The correct way is to import the wavfile submodule from scipy.io asfrom scipy.io import wavfile.Final Answer:
from scipy.io import wavfile -> Option AQuick Check:
Correct import syntax = from scipy.io import wavfile [OK]
Hint: Use 'from scipy.io import wavfile' to access read/write [OK]
Common Mistakes:
- Trying to import read directly
- Using dot notation incorrectly in import
- Swapping import order
3. What will be the output shape of the data array when you read a stereo WAV file with 44100 samples per channel using
scipy.io.wavfile.read?medium
Solution
Step 1: Understand stereo audio data shape
Stereo audio has two channels, so data shape is (samples, channels).Step 2: Calculate shape for 44100 samples
With 44100 samples per channel and 2 channels, shape is (44100, 2).Final Answer:
(44100, 2) -> Option BQuick Check:
Stereo shape = (samples, 2) [OK]
Hint: Stereo data shape is (samples, 2) always [OK]
Common Mistakes:
- Confusing channels and samples order
- Assuming shape is (2, samples)
- Thinking stereo data is flattened
4. You try to save a NumPy array with float values using
scipy.io.wavfile.write but get an error. What is the likely cause?medium
Solution
Step 1: Check data type requirements for write()
scipy.io.wavfile.writeexpects integer arrays (e.g., int16) for audio data.Step 2: Identify error cause
Using float arrays causes errors because WAV format stores integers, so conversion is needed.Final Answer:
The array must be integer type, not float -> Option DQuick Check:
write() needs int arrays [OK]
Hint: Convert floats to int before writing WAV [OK]
Common Mistakes:
- Ignoring data type and writing floats directly
- Forgetting sample rate argument
- Misunderstanding array shape requirements
5. You want to double the speed of a WAV audio file using
scipy.io.wavfile. Which approach correctly achieves this?hard
Solution
Step 1: Understand speed and sample rate relation
Speed changes by adjusting sample rate: doubling sample rate doubles playback speed.Step 2: Apply correct method
Keep audio data unchanged but write with double the original sample rate to speed up playback.Final Answer:
Double the sample rate value and write the original data unchanged -> Option AQuick Check:
Speed ∝ sample rate, double rate doubles speed [OK]
Hint: Change sample rate to speed up audio, not data length [OK]
Common Mistakes:
- Skipping samples instead of changing sample rate
- Halving sample rate to speed up (actually slows down)
- Reversing data does not change speed
