[파이썬] scipy WAV 파일 읽기/쓰기

Python provides several libraries for working with audio files, including WAV files. One of the most popular libraries for audio processing is scipy. In this blog post, we will explore how to read and write WAV files using scipy in Python.

Reading WAV files

To read a WAV file using scipy, we need to use the scipy.io.wavfile module. Here’s an example of how to read a WAV file:

import scipy.io.wavfile as wav

# Specify the path to the WAV file
file_path = 'audio.wav'

# Read the WAV file
sample_rate, audio_data = wav.read(file_path)

# Printing the sample rate and audio data
print("Sample Rate:", sample_rate)
print("Audio Data:", audio_data)

In the code above, we imported the wavfile module from scipy.io and then used the read function to read the WAV file. The read function returns the sample rate and audio data as separate variables.

Writing WAV files

To write a WAV file using scipy, we can also use the scipy.io.wavfile module. Here’s an example of how to write audio data to a WAV file:

import scipy.io.wavfile as wav
import numpy as np

# Sample rate and audio data
sample_rate = 44100
audio_data = np.random.uniform(-1, 1, size=(sample_rate,))

# Specify the path to save the WAV file
output_file = 'output.wav'

# Write the audio data to a WAV file
wav.write(output_file, sample_rate, audio_data)

In the code above, we generated random audio data using NumPy’s random.uniform function. We then used the write function from wavfile module to write the audio data to a WAV file.

Conclusion

In this blog post, we explored how to read and write WAV files using scipy in Python. The scipy.io.wavfile module provides a convenient way to work with audio data in WAV format. With scipy, you can easily read and write WAV files for audio processing tasks.