Reputation: 51
I am looking for a way to convert a waveform that is composed of time on the x axis and amplitude on the y axis into a wav or any other audio file. Code or a python library is much appreciated
Here is the waveform that I want to convert
Upvotes: 2
Views: 2482
Reputation: 1245
You can use the standard wave
library. Here is a function that I use. You can modify it further if you need more channels or a different sample width.
import wave
import struct
def signal_to_wav(signal, fname, Fs):
"""Convert a numpy array into a wav file.
Args
----
signal : 1-D numpy array
An array containing the audio signal.
fname : str
Name of the audio file where the signal will be saved.
Fs: int
Sampling rate of the signal.
"""
data = struct.pack('<' + ('h'*len(signal)), *signal)
wav_file = wave.open(fname, 'wb')
wav_file.setnchannels(1)
wav_file.setsampwidth(2)
wav_file.setframerate(Fs)
wav_file.writeframes(data)
wav_file.close()
Some links to the documentation:
https://docs.python.org/3/library/wave.html
https://docs.python.org/2/library/wave.html
Upvotes: 4