spplugin module
A python module for plugin-based audio file I/O based on spPlugin which supports several sound formats including WAV, AIFF, MP3, Ogg Vorbis, FLAC, ALAC, raw, and more.
Example
The following is the example plotting the waveform of an input audio file.
import os
import sys
import spplugin
import numpy as np
import matplotlib.pyplot as plt
def plotfilebyplugin(filename):
with spplugin.open(filename, 'r') as pf:
nchannels = pf.getnchannels()
samprate = pf.getsamprate()
sampbit = pf.getsampbit()
nframes = pf.getnframes()
duration = nframes / samprate
y = pf.createndarray(nframes * nchannels)
nread = pf.read(y)
print('nread = %d' % nread)
y.resize((nframes, nchannels))
x = np.linspace(0.0, duration, nframes)
for i in range(nchannels):
plt.plot(x, y[:,i])
plt.xlim(0.0, duration)
plt.xlabel('Time [s]')
plt.ylabel('Amplitude (normalized)')
plt.show()
if __name__ == '__main__':
if len(sys.argv) <= 1:
print('usage: %s filename'
% os.path.basename(sys.argv[0]), file=sys.stderr)
quit()
plotfilebyplugin(sys.argv[1])
The following is the another example using a high-level function of
audioread()
which is similar to MATLAB’s one
(version 0.7.16+).
import os
import sys
import spplugin
import spaudio
def audioreadexample(filename):
data, samprate, params = spplugin.audioread(filename)
print('samprate = ' + str(samprate) + ', params =\n' + str(params))
with spaudio.open('wo', params=params) as a:
nwframes = a.writeframes(data)
print('write frames = %d' % nwframes)
if __name__ == '__main__':
if len(sys.argv) <= 1:
print('usage: %s filename'
% os.path.basename(sys.argv[0]), file=sys.stderr)
quit()
audioreadexample(sys.argv[1])
The following is the ‘write’ version of above example using a high-level
function of audiowrite()
which is similar to MATLAB’s one
(version 0.7.16+).
import os
import sys
import spplugin
import spaudio
def audiowriteexample(filename):
duration = 2.0
with spaudio.open('ro', nchannels=2, samprate=44100) as a:
nframes = round(duration * a.getsamprate())
data = a.readframes(nframes, channelwise=True)
print('nread = %d' % len(data))
nwframes = spplugin.audiowrite(filename, data, a.getsamprate())
print('write frames = %d' % nwframes)
if __name__ == '__main__':
if len(sys.argv) <= 1:
print('usage: %s filename'
% os.path.basename(sys.argv[0]), file=sys.stderr)
quit()
audiowriteexample(sys.argv[1])
- exception spplugin.BogusFileError[source]
Bases:
Error
Exception raised if the audio file is bogus.
- exception spplugin.FileTypeError[source]
Bases:
Error
Exception raised if the specified file type is not accepted.
- exception spplugin.NChannelsError[source]
Bases:
Error
Exception raised if the specified number of channels is not accepted.
- exception spplugin.NFramesRequiredError[source]
Bases:
Error
Exception raised if the total number of frames is required to use the plugin.
- exception spplugin.SampleBitError[source]
Bases:
Error
Exception raised if the specified bits/sample is not accepted.
- exception spplugin.SampleRateError[source]
Bases:
Error
Exception raised if the specified sample rate is not accepted.
- class spplugin.SpFilePlugin[source]
Bases:
object
A class for audio file I/O. This class is similar to one provided by the standard libraries such as aifc, wave, or sunau. The important difference is that
set*()
functions must be called beforeopen()
in this class. You can set parameters by using optional arguments ofopen()
function.- copyarray2raw(inarray, sampwidth, bigendian_or_signed8bit=False)[source]
Copies raw array (array.array) contents to a new raw bytes (bytearray) data.
- Parameters:
inarray (array.array) – Input array object.
sampwidth (int) – bytes/sample of output data.
bigendian_or_signed8bit (bool, optional) – Specify
True
if endianness of output data is big endian (16- or 32-bit case) or data type of output data is signed 8-bit (8-bit case).
- Returns:
A bytearray class object which contains converted data.
- Return type:
bytearray
- copyraw2array(rawdata, sampwidth, bigendian_or_signed8bit=False)[source]
Copies raw bytes (bytearray) data contents to a new raw array (array.array).
- Parameters:
rawdata (bytes or bytearray) – Input bytes or bytearray object.
sampwidth (int) – bytes/sample of rawdata
bigendian_or_signed8bit (bool, optional) – Specify
True
if endianness of rawdata is big endian (16- or 32-bit case) or data type of rawdata (8-bit case) is signed 8-bit.
- Returns:
An array class object which contains converted data.
- Return type:
array.array
- createarray(length, nframesflag=False)[source]
Creates a double-precision array for the current file settings.
- Parameters:
length – A length of the array. Note that this length is not identical to the number of frames (length = nframes * nchannels). If you want to specify the number of frames, the second argument must be
True
.nframesflag (bool, optional) –
True
makes the first argument be treated as the number of frames.
- Returns:
An array class object for the current file settings.
- Return type:
array.array
- createndarray(length, nframesflag=False, channelwise=False)[source]
Creates a numpy double-precision array for the current file settings.
- Parameters:
length – A length of the array. Note that this length is not identical to the number of frames (length = nframes * nchannels). If you want to specify the number of frames, the second argument must be
True
.nframesflag (bool, optional) –
True
makes the first argument be treated as the number of frames.channelwise (bool, optional) –
True
resizes the returned array into (nframes, nchannels) matrix. This argument is introduced in Version 0.7.16.
- Returns:
An ndarray class object for the current file settings.
- Return type:
numpy.ndarray
- createrawarray(length, nframesflag=False)[source]
Creates a raw array for the current file settings.
- Parameters:
length – A length of the array. Note that this length is not identical to the number of frames (length = nframes * nchannels). If you want to specify the number of frames, the second argument must be
True
.nframesflag (bool, optional) –
True
makes the first argument be treated as the number of frames.
- Returns:
An array class object for the current file settings.
- Return type:
array.array
- createrawndarray(length, nframesflag=False, channelwise=False)[source]
Creates a raw numpy ndarray for the current file settings.
- Parameters:
length – A length of the array. Note that this length is not identical to the number of frames (length = nframes * nchannels). If you want to specify the number of frames, the second argument must be
True
.nframesflag (bool, optional) –
True
makes the first argument be treated as the number of frames.channelwise (bool, optional) –
True
resizes the returned array into (nframes, nchannels) matrix. This argument is introduced in Version 0.7.16.
- Returns:
An ndarray class object for the current file settings.
- Return type:
numpy.ndarray
- getarraytypecode()[source]
Gets the type code for python array to store double-precision data.
- Returns:
A type code of a double-precision array for the current settings.
- Return type:
char
- getcompname(decodebytes=False)[source]
Returns human-readable name of compression type. Currently,
'not compressed'
(decodebytes =True
) orb'not compressed'
(decodebytes =False
) will be returned.
- getcomptype(decodebytes=False)[source]
Returns compression type. Currently,
'NONE'
(decodebytes =True
) orb'NONE'
(decodebytes =False
) will be returned.
- getfiledesc()[source]
Gets file description of the current file. For example,
'Microsoft PCM'
for a WAV file in PCM format.
- getmark(id)[source]
Does nothing (for compatibility with standard libraries such as aifc, wave, and sunau).
- getmarkers()[source]
Does nothing (for compatibility with standard libraries such as aifc, wave, and sunau).
- getndarraydtype()[source]
Gets the dtype string for numpy ndarray to store double-precision data.
- Returns:
A dtype string for the current settings.
- Return type:
string
- getparams()[source]
Gets supported all parameters of the current file in dict object.
- Returns:
A dict object including all parameters of the current file whose keys are
'nchannels'
,'sampbit'
,'samprate'
,'nframes'
,'filetype'
, and'songinfo'
.- Return type:
dict
- getparamstuple(decodebytes=False)[source]
Gets supported all parameters of the current file in namedtuple object.
- Parameters:
decodebytes (bool, optional) –
True
decodes bytes objects into string objects obtained bygetcomptype()
andgetcompname()
. The standard libraries of wave and sunau expect a decoded string object while the standard aifc library expects a bytes object.- Returns:
A namedtuple object including all parameters of the current file whose entries are
(nchannels, sampwidth, framerate, nframes, comptype, compname)
. This object is compatible with the argument ofsetparams()
of standard libraries such as aifc, wave, or sunau.- Return type:
namedtuple
- getrawarraytypecode()[source]
Gets the type code for python array to store raw data.
- Returns:
A type code for the current settings.
- Return type:
char
- getrawndarraydtype()[source]
Gets the dtype string for numpy ndarray to store raw data.
- Returns:
A dtype string for the current settings.
- Return type:
string
- open(filename, mode, *, pluginname=None, samprate=0, sampbit=0, nchannels=0, filetype=None, songinfo=None, params=None)[source]
Opens the file associated with the filename by using a plugin.
- Parameters:
filename (str) – The name of the file to open.
mode (str) – The opening mode.
'r'
means read mode,'w'
means write mode.pluginname (str, optional) – The name of the plugin used when this function cannot find the suitable plugin. Otherwise,
SuitableNotFoundError
exception will be raised. If you want to read a raw file, specify'input_raw'
.samprate (double, optional) – Sample rate.
sampbit (int, optional) – Bits/sample.
nchannels (int, optional) – The number of channels.
filetype (str, optional) – File type string.
songinfo (dict, optional) – Song information.
params (dict, optional) – All acceptable parameters in dict format.
- Raises:
SuitableNotFoundError – If no suitable plugin is found.
- read(data, weight=1.0, offset=0, length=0)[source]
Reads data to a double-precision array from the audio file.
- Parameters:
data (bytearray, array.array or numpy.ndarray) – A double-precision array to receive data from the audio file.
weight (double, optional) – A weighting factor multiplied to data after reading.
offset (int, optional) – Optional offset location for the array.
length (int, optional) – Optional read length for the array.
- Returns:
The read size if successful, -1 otherwise.
- Return type:
int
Note
The keyword arguments of offset and length were introduced in Version 0.7.15.
- readframes(nframes, weight=1.0, arraytype='ndarray', channelwise=False)[source]
Reads and returns the next nframes data of a double-precision array.
- Parameters:
nframes (int) – The number of frames to read. A negative value means the total number of frames.
weight (double, optional) – A weighting factor multiplied to data after reading.
arraytype (str, optional) – The type of output array. The value must be
'ndarray'
(default),'array'
, or'bytearray'
.channelwise (bool, optional) –
True
resizes the returned ndarray into (nframes, nchannels) matrix. This argument is valid only inarraytype='ndarray'
case.
- Returns:
The output array object containing read data.
- Return type:
numpy.ndarray, array.array or bytearray
Note
This function was introduced in Version 0.7.16.
- readraw(data, offset=0, length=0)[source]
Reads raw data from the audio file.
- Parameters:
data (bytearray, array.array or numpy.ndarray) – A raw array to receive raw data from the audio file.
offset (int, optional) – Optional offset location for the array.
length (int, optional) – Optional read length for the array.
- Returns:
The read size if successful, -1 otherwise.
- Return type:
int
Note
The keyword arguments of offset and length were introduced in Version 0.7.15.
- readrawframes(nframes, arraytype='ndarray', channelwise=False)[source]
Reads and returns the next nframes data of a raw array.
- Parameters:
nframes (int) – The number of frames to read. A negative value means the total number of frames.
arraytype (str, optional) – The type of output array. The value must be
'ndarray'
(default),'array'
, or'bytearray'
.channelwise (bool, optional) –
True
resizes the returned ndarray into (nframes, nchannels) matrix. This argument is valid only inarraytype='ndarray'
case.
- Returns:
The output array object containing read data.
- Return type:
numpy.ndarray, array.array or bytearray
Note
This function was introduced in Version 0.7.16.
- setmark(id, pos, name)[source]
Does nothing (for compatibility with standard libraries such as aifc, wave, and sunau).
- setparams(params)[source]
Sets supported all parameters described in dict or namedtuple object to the file.
- Parameters:
params (dict) – a dict object of parameters whose keys are
'nchannels'
,'sampbit'
,'samprate'
,'nframes'
,'filetype'
, or'songinfo'
. The namedtuple generated by standard libraries such as aifc, wave, or sunau is also acceptable.
- write(data, weight=1.0, offset=0, length=0)[source]
Writes data of a double-precision array to the audio file.
- Parameters:
data (bytearray, array.array or numpy.ndarray) – A double-precision array to send data to the audio file.
weight (double, optional) – A weighting factor multiplied to data before writing.
offset (int, optional) – Optional offset location for the array.
length (int, optional) – Optional write length for the array.
- Returns:
The written size if successful, -1 otherwise.
- Return type:
int
Note
The keyword arguments of offset and length were introduced in Version 0.7.15.
- writeframes(data, weight=1.0)[source]
Writes data of a double-precision array to the audio file.
- Parameters:
data (bytearray, array.array or numpy.ndarray) – A double-precision array to send data to the audio file.
weight (double, optional) – A weighting factor multiplied to data before writing.
- Returns:
The written number of frames if successful, -1 otherwise.
- Return type:
int
Note
This function was introduced in Version 0.7.16.
- writeraw(data, offset=0, length=0)[source]
Writes data of a raw array to the audio file.
- Parameters:
data (bytearray, array.array or numpy.ndarray) – A raw array to send data to the audio file.
offset (int, optional) – Optional offset location for the array.
length (int, optional) – Optional write length for the array.
- Returns:
The written size if successful, -1 otherwise.
- Return type:
int
Note
The keyword arguments of offset and length were introduced in Version 0.7.15.
- writerawframes(data)[source]
Writes data of a raw array to the audio file.
- Parameters:
data (bytearray, array.array or numpy.ndarray) – A raw array to send data to the audio file.
- Returns:
The written number of frames if successful, -1 otherwise.
- Return type:
int
Note
This function was introduced in Version 0.7.16.
- exception spplugin.SuitableNotFoundError[source]
Bases:
Error
Exception raised if no suitable plugin is found.
- spplugin.audioread(filename, samples=(0, - 1), datatype='double', *, weight=1.0, arraytype='ndarray', channelwise=True, getparamstuple=False, decodebytes=False, pluginname=None, samprate=0, sampbit=0, nchannels=0, filetype=None, params=None)[source]
Reads contents of an audio file by using a plugin.
- Parameters:
filename (str) – The name of the file to open.
samples (tuple, optional) – The audio sample (frame) range which has the form
(start, finish)
. Iffinish
is negative, it means the end of the file.datatype (str, optional) – The format of the output data.
'double'
case makesreadframes()
method used and'raw'
case makesreadrawframes()
method used internally. Note that'raw'
case ignores weight argument.weight (double, optional) – A weighting factor multiplied to data after reading.
arraytype (str, optional) – The type of output array. The value must be
'ndarray'
(default),'array'
, or'bytearray'
.channelwise (bool, optional) –
True
resizes the returned ndarray into (nframes, nchannels) matrix. This argument is valid only inarraytype='ndarray'
case.getparamstuple (bool, optional) –
True
makesgetparamstuple()
used internally.decodebytes (bool, optional) –
True
decodes bytes objects into string objects in callinggetparamstuple()
method. This argument is valid only ingetparamstuple=True
case.pluginname (str, optional) – The name of the plugin used when this function cannot find the suitable plugin. Otherwise,
SuitableNotFoundError
exception will be raised. If you want to read a raw file, specify'input_raw'
.samprate (double, optional) – Sample rate.
sampbit (int, optional) – Bits/sample.
nchannels (int, optional) – The number of channels.
filetype (str, optional) – File type string.
songinfo (dict, optional) – Song information.
params (dict, optional) – All acceptable parameters in dict format.
- Returns:
The output tuple whose elements are the following.
numpy.ndarray, array.array or bytearray – The output array object containing read data.
double – Sample rate of the audio file.
dict or namedtuple – If
getparamstuple=False
, A dict object same as that obtained bygetparams()
method will be returned. Ifgetparamstuple=True
, A namedtuple object same as that obtained bygetparamstuple()
method will be returned.
- Return type:
tuple
- Raises:
SuitableNotFoundError – If no suitable plugin is found.
Note
This function was introduced in Version 0.7.16.
- spplugin.audiowrite(filename, data, samprate=0, nchannels=0, sampbit=0, *, datatype=None, weight=1.0, offset=0, length=0, pluginname=None, filetype=None, songinfo=None, params=None)[source]
Writes data to an audio file by using a plugin.
- Parameters:
filename (str) – The name of the file to open.
data (bytearray, array.array or numpy.ndarray) – A array to send data to the audio file.
samprate (double, optional) – Sample rate.
nchannels (int, optional) – The number of channels.
sampbit (int, optional) – Bits/sample.
datatype (str, optional) – The format of the input data.
'double'
case makeswrite()
method used and'raw'
case makeswriteraw()
method used internally. Note that'raw'
case ignores weight argument. In some array types, this parameter can be detected automatically.weight (double, optional) – A weighting factor multiplied to data before writing.
offset (int, optional) – Optional offset location for the array.
length (int, optional) – Optional write length for the array.
pluginname (str, optional) – The name of the plugin used when this function cannot find the suitable plugin. Otherwise,
SuitableNotFoundError
exception will be raised. If you want to write data to a raw file, specify'output_raw'
.filetype (str, optional) – File type string.
songinfo (dict, optional) – Song information.
params (dict, optional) – All acceptable parameters in dict format.
- Returns:
The written number of frames if successful, -1 otherwise.
- Return type:
int
- Raises:
SuitableNotFoundError – If no suitable plugin is found.
Note
This function was introduced in Version 0.7.16.
- spplugin.getplugindesc(name)[source]
Gets short description of the plugin which has a name specified.
- spplugin.getplugininfo(name)[source]
Gets detailed information of the plugin which has a name specified.
- spplugin.open(filename, mode, *, pluginname=None, samprate=0, sampbit=0, nchannels=0, filetype=None, songinfo=None, params=None)[source]
Opens the file associated with the filename by using a plugin. This function may be used in a
with
statement.- Parameters:
filename (str) – The name of the file to open.
mode (str) – The opening mode.
'r'
means read mode,'w'
means write mode.pluginname (str, optional) – The name of the plugin used when this function cannot find the suitable plugin. Otherwise,
SuitableNotFoundError
exception will be raised. If you want to read a raw file, specify'input_raw'
.samprate (double, optional) – Sample rate.
sampbit (int, optional) – Bits/sample.
nchannels (int, optional) – The number of channels.
filetype (str, optional) – File type string.
songinfo (dict, optional) – Song information.
params (dict, optional) – All acceptable parameters in dict format.
- Returns:
A new instance of
SpFilePlugin
class.- Return type:
- Raises:
SuitableNotFoundError – If no suitable plugin is found.