简体   繁体   中英

python waveform to WAV file converter

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM