Skip to content

Instantly share code, notes, and snippets.

@imcomking
Last active May 7, 2020 04:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imcomking/43dc18024f29a2c63d1931db6801fe87 to your computer and use it in GitHub Desktop.
Save imcomking/43dc18024f29a2c63d1931db6801fe87 to your computer and use it in GitHub Desktop.
wave file read & write by Python Built-in function
import numpy as np
import wave
import matplotlib.pyplot as plt
import sounddevice as sd
class SoundFile:
def __init__(self, file_name=None):
# https://docs.python.org/3.6/library/wave.html
pass
def write(self, file_name, signal, nchannels=1, sampwidth=2, framerate=44100, duration_sec = 4, comptype="NONE", compname="noncompressed"):
file = wave.open(file_name, 'wb')
file.setparams( ( nchannels, sampwidth, framerate, framerate * duration_sec, comptype, compname) )
file.writeframes( signal )
file.close()
def read(self, file_name):
file = wave.open(file_name, 'rb')
nchannels, sampwidth, framerate, nframes, comptype, compname = file.getparams()
duration_sec = nframes / framerate
signal = file.readframes( nframes )
signal = np.frombuffer(signal)
file.close()
return signal, nchannels, sampwidth, framerate, duration_sec, nframes, comptype, compname
@imcomking
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment