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])
exception spplugin.BogusFileError[source]

Bases: spplugin.Error

Exception raised if the audio file is bogus.

exception spplugin.Error[source]

Bases: Exception

Base exception class for spplugin.

exception spplugin.FileError[source]

Bases: spplugin.Error

Exception raised by audio file problems.

exception spplugin.FileTypeError[source]

Bases: spplugin.Error

Exception raised if the specified file type is not accepted.

exception spplugin.NChannelsError[source]

Bases: spplugin.Error

Exception raised if the specified number of channels is not accepted.

exception spplugin.SampleBitError[source]

Bases: spplugin.Error

Exception raised if the specified bits/sample is not accepted.

exception spplugin.SampleRateError[source]

Bases: spplugin.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 before open() in this class. You can set parameters by using optional arguments of open() function.

appendsonginfo(songinfo)[source]

Appends song information to the current internal information.

close()[source]

Closes the current audio file.

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) – 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) – 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 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) – 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)[source]

Creates a numpy double 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) – True makes the first argument be treated as the number of frames.

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) – 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)[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) – True makes the first argument be treated as the number of frames.

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 array.

Returns

A type code of double array for the current settings.

Return type

char

getcompname(decodebytes=False)[source]

Returns human-readable name of compression type. Currently, 'not compressed' (decodebytes = True) or b'not compressed' (decodebytes = False) will be returned.

getcomptype(decodebytes=False)[source]

Returns compression type. Currently, 'NONE' (decodebytes = True) or b'NONE' (decodebytes = False) will be returned.

getfiledesc()[source]

Gets file description of the current file.

getfilefilter()[source]

Gets file filter (e.g. '*.wav') of the current file.

getfiletype()[source]

Gets file type of the current file.

getframerate()[source]

Gets sample rate of the current file.

getlength()[source]

Gets the total length of the current file.

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).

getnchannels()[source]

Gets the number of channels of the current file.

getndarraydtype()[source]

Gets the dtype string for numpy ndarray to store double array.

Returns

A dtype string for the current settings.

Return type

string

getnframes()[source]

Gets the total number of frames of the current file.

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', 'length', 'filetype', and 'songinfo'.

Return type

dict

getparamstuple(decodebytes=False)[source]

Gets supported all parameters of the current file in namedtuple object.

Parameters

decodebytes (bool) – True decodes bytes objects into string objects obtained by getcomptype() and getcompname() . 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 of setparams() of standard libraries such as aifc, wave, or sunau.

Return type

namedtuple

getplugindesc()[source]

Gets the short description of the plugin currently used.

getpluginid()[source]

Gets the ID of the plugin currently used.

getplugininfo()[source]

Gets the detailed information of the plugin currently used.

getpluginname()[source]

Gets the name of the plugin currently used.

getpluginversion()[source]

Gets the version of the plugin currently used.

getrawarraytypecode()[source]

Gets the type code for python array.

Returns

A type code for the current settings.

Return type

char

getrawndarraydtype()[source]

Gets the dtype string for numpy ndarray.

Returns

A dtype string for the current settings.

Return type

string

getrawsampbit()[source]

Gets the bits/sample for a raw buffer.

getrawsampwidth()[source]

Gets the bytes/sample for a raw buffer.

getsampbit()[source]

Gets bits/sample of the current file. sampbit = 33 means 32bit float.

getsamprate()[source]

Gets sample rate of the current file.

getsampwidth()[source]

Gets bytes/sample of the current file.

getsonginfo()[source]

Gets song information of the current file.

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) – The name of the plugin used when this function cannot find the suitable plugin.

  • samprate (double) – Sample rate.

  • sampbit (int) – Bits/sample.

  • nchannels (int) – The number of channels.

  • filetype (str) – File type string.

  • songinfo (dict) – Song information.

  • params (dict) – All above parameters in dict format.

read(data, weight=1.0, offset=0, length=0)[source]

Reads data to double array from the audio file.

Parameters
  • data (bytearray, array.array or numpy.ndarray) – A buffer of double array to receive data from the audio file.

  • weight (double) – A weighting factor multiplied to data after reading.

  • offset (int) – Optional offset location for the buffer.

  • length (int) – Optional read length for the buffer.

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.5.

readraw(data, offset=0, length=0)[source]

Reads raw data from the audio file.

Parameters
  • data (bytearray, array.array or numpy.ndarray) – A buffer to receive raw data from the audio file.

  • offset (int) – Optional offset location for the buffer.

  • length (int) – Optional read length for the buffer.

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.5.

rewind()[source]

Rewinds to the beginning of the file.

setcomptype(encodestr=True)[source]

Sets compression type. Currently, this parameter is ignored.

setfiletype(filetype)[source]

Sets file type to the file.

setframerate(samprate)[source]

Sets sample rate to the file.

setlength(length)[source]

Sets the total length of the file.

setmark(id, pos, name)[source]

Does nothing (for compatibility with standard libraries such as aifc, wave, and sunau).

setnchannels(nchannels)[source]

Sets the number of channels to the file.

setnframes(length)[source]

Sets the total number of frames of the current file.

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', 'length', 'filetype', or 'songinfo'. The namedtuple generated by standard libraries such as aifc, wave, or sunau is also acceptable.

setpos(pos)[source]

Seeks to the specified position.

Parameters

pos – a position to seek.

setsampbit(sampbit)[source]

Sets bits/sample to the file. sampbit = 33 means 32bit float.

setsamprate(samprate)[source]

Sets sample rate to the file.

setsampwidth(sampwidth, floatflag=False)[source]

Sets bytes/sample of the current file.

setsonginfo(songinfo)[source]

Sets song information to the file.

tell()[source]

Gets the current position in the file.

write(data, weight=1.0, offset=0, length=0)[source]

Writes data of double array to the audio file.

Parameters
  • data (bytearray, array.array or numpy.ndarray) – A buffer of double array to send data to the audio file.

  • weight (double) – A weighting factor multiplied to data before writing.

  • offset (int) – Optional offset location for the buffer.

  • length (int) – Optional write length for the buffer.

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.5.

writeraw(data, offset=0, length=0)[source]

Writes raw data to the audio file.

Parameters
  • data (bytearray, array.array or numpy.ndarray) – A buffer to send raw data to the audio file.

  • offset (int) – Optional offset location for the buffer.

  • length (int) – Optional write length for the buffer.

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.5.

exception spplugin.SuitableNotFoundError[source]

Bases: spplugin.Error

Exception raised if no suitable plugin is found.

exception spplugin.TotalLengthRequiredError[source]

Bases: spplugin.Error

Exception raised if the total length is required to use the plugin.

exception spplugin.WrongPluginError[source]

Bases: spplugin.Error

Exception raised by a wrong plugin.

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) – The name of the plugin used when this function cannot find the suitable plugin.

  • samprate (double) – Sample rate.

  • sampbit (int) – Bits/sample.

  • nchannels (int) – The number of channels.

  • filetype (str) – File type string.

  • songinfo (dict) – Song information.

  • params (dict) – All above parameters in dict format.

Returns

A new instance of SpFilePlugin class.

Return type

SpFilePlugin