Examples

spaudio

Fullduplex I/O

iotest.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import spaudio

a = spaudio.SpAudio()

a.setnchannels(2)
a.setsamprate(44100)
a.setbuffersize(2048)

nloop = 500
b = bytearray(4096)

a.open('r')
a.open('w')

for i in range(nloop):
    a.readraw(b)
    a.writeraw(b)

a.close()

Fullduplex I/O (using with statement; version 0.7.15+)

iotestwith.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.15+ required.

import spaudio

with spaudio.open('rw', nchannels=2, samprate=44100, buffersize=2048) as a:
    nloop = 500
    b = bytearray(4096)

    for i in range(nloop):
        a.readraw(b)
        a.writeraw(b)

Read and plot (Python array version)

readplot.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import spaudio
import matplotlib.pyplot as plt

a = spaudio.SpAudio()

a.setnchannels(1)
a.setsamprate(8000)

a.open('ro')

b = a.createarray(16000)

nread = a.read(b)
print('nread = %d' % nread)

a.close()

a.open('wo')

nwrite = a.write(b)
print('nwrite = %d' % nwrite)

a.close()

plt.plot(b)
plt.show()

Read and plot (raw data version)

readplotraw.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import spaudio
import matplotlib.pyplot as plt

a = spaudio.SpAudio()

a.setnchannels(1)
a.setsamprate(8000)

a.open('ro')

b = a.createrawarray(16000)

nread = a.readraw(b)
print('nread = %d' % nread)

a.close()

a.open('wo')

nwrite = a.writeraw(b)
print('nwrite = %d' % nwrite)

a.close()

plt.plot(b)
plt.show()

Read and plot (NumPy ndarray version)

readndarray.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import spaudio

a = spaudio.SpAudio()

a.setnchannels(1)
a.setsamprate(8000)

a.open('ro')

y = a.createndarray(16000)

nread = a.read(y)
print('nread = %d' % nread)

a.close()

a.open('wo')

nwrite = a.write(y)
print('nwrite = %d' % nwrite)

a.close()

x = np.linspace(0.0, 2.0, 16000)
plt.plot(x, y)
plt.xlim(0.0, 2.0)
plt.xlabel('Time [s]')
plt.ylabel('Amplitude (normalized)')
plt.show()

Read and plot (NumPy ndarray version; using with statement; version 0.7.16+)

readndarray2.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.16+ required.

import numpy as np
import matplotlib.pyplot as plt
import spaudio

with spaudio.open('ro', nchannels=2, samprate=44100) as a:
    y = a.readframes(44100, channelwise=True)
    print('nread = %d' % len(y))

    x = np.linspace(0.0, 1.0, 44100)
    for i in range(a.getnchannels()):
        plt.plot(x, y[:, i])
    plt.xlabel('Time [s]')
    plt.ylabel('Amplitude (normalized)')
    plt.show()

Read and plot (NumPy raw ndarray version)

readrawndarray.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import spaudio

a = spaudio.SpAudio()

a.setnchannels(1)
a.setsamprate(8000)

a.open('ro')

y = a.createrawndarray(16000)

nread = a.readraw(y)
print('nread = %d' % nread)

a.close()

a.open('wo')

nwrite = a.writeraw(y)
print('nwrite = %d' % nwrite)

a.close()

x = np.linspace(0.0, 2.0, 16000)
plt.plot(x, y)
plt.xlim(0.0, 2.0)
plt.xlabel('Time [s]')
plt.ylabel('Amplitude (raw)')
plt.show()

Play a WAV file

playfromwav.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import wave
import spaudio


def playfromwav(filename):
    with wave.open(filename, 'rb') as wf:
        nchannels = wf.getnchannels()
        samprate = wf.getframerate()
        sampwidth = wf.getsampwidth()
        nframes = wf.getnframes()
        print('nchannels = %d, samprate = %d, sampwidth = %d, nframes = %d'
              % (nchannels, samprate, sampwidth, nframes))

        a = spaudio.SpAudio()

        a.setnchannels(nchannels)
        a.setsamprate(samprate)
        a.setsampwidth(sampwidth)

        b = wf.readframes(nframes)

        a.open('wo')

        nwrite = a.writeraw(b)
        print('nwrite = %d' % nwrite)

        a.close()


if __name__ == '__main__':
    if len(sys.argv) <= 1:
        print('usage: %s filename'
              % os.path.basename(sys.argv[0]), file=sys.stderr)
        quit()

    playfromwav(sys.argv[1])

Play a WAV file (using with statement; version 0.7.15+)

playfromwav2.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.15+ required.

import os
import sys
import wave
import spaudio


def playfromwav2(filename):
    with wave.open(filename, 'rb') as wf:
        paramstuple = wf.getparams()
        print('nchannels = %d, framerate = %d, sampwidth = %d, nframes = %d'
              % (paramstuple.nchannels, paramstuple.framerate,
                 paramstuple.sampwidth, paramstuple.nframes))

        with spaudio.open('wo', params=paramstuple) as a:
            b = wf.readframes(paramstuple.nframes)
            nwrite = a.writeraw(b)
            print('nwrite = %d' % nwrite)


if __name__ == '__main__':
    if len(sys.argv) <= 1:
        print('usage: %s filename'
              % os.path.basename(sys.argv[0]), file=sys.stderr)
        quit()

    playfromwav2(sys.argv[1])

Play a WAV file with callback

playfromwavcb.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import wave
import spaudio


def myaudiocb(audio, cbtype, cbdata, args):
    if cbtype == spaudio.OUTPUT_POSITION_CALLBACK:
        position = cbdata
        samprate = args[0]
        nframes = args[1]
        position_s = float(position) / float(samprate)
        total_s = float(nframes) / float(samprate)
        sys.stdout.write('Time: %.3f / %.3f\r' % (position_s, total_s))
    elif cbtype == spaudio.OUTPUT_BUFFER_CALLBACK:
        buf = cbdata
        # print('OUTPUT_BUFFER_CALLBACK: buffer type = %s, size = %d' % (type(buf), len(buf)))
    return True


def playfromwav(filename):
    with wave.open(filename, 'rb') as wf:
        nchannels = wf.getnchannels()
        samprate = wf.getframerate()
        sampwidth = wf.getsampwidth()
        nframes = wf.getnframes()
        print('nchannels = %d, samprate = %d, sampwidth = %d, nframes = %d'
              % (nchannels, samprate, sampwidth, nframes))

        a = spaudio.SpAudio()

        a.setbuffersize(1024)
        a.setnchannels(nchannels)
        a.setsamprate(samprate)
        a.setsampwidth(sampwidth)

        b = wf.readframes(nframes)

        a.setcallback(spaudio.OUTPUT_POSITION_CALLBACK | spaudio.OUTPUT_BUFFER_CALLBACK,
                      myaudiocb, samprate, nframes)

        a.open('wo')

        nwrite = a.writeraw(b)
        # print('nwrite = %d' % nwrite)

        a.close()


if __name__ == '__main__':
    if len(sys.argv) <= 1:
        print('usage: %s filename'
              % os.path.basename(sys.argv[0]), file=sys.stderr)
        quit()

    playfromwav(sys.argv[1])

Play a WAV file with callback (using with statement; version 0.7.15+)

playfromwavcb2.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import wave
import spaudio


def myaudiocb(audio, cbtype, cbdata, args):
    if cbtype == spaudio.OUTPUT_POSITION_CALLBACK:
        position = cbdata
        samprate = args[0]
        nframes = args[1]
        position_s = float(position) / float(samprate)
        total_s = float(nframes) / float(samprate)
        sys.stdout.write('Time: %.3f / %.3f\r' % (position_s, total_s))
    elif cbtype == spaudio.OUTPUT_BUFFER_CALLBACK:
        buf = cbdata
        # print('OUTPUT_BUFFER_CALLBACK: buffer type = %s, size = %d' % (type(buf), len(buf)))
    return True


def playfromwav2(filename):
    with wave.open(filename, 'rb') as wf:
        paramstuple = wf.getparams()
        print('nchannels = %d, samprate = %d, sampwidth = %d, nframes = %d'
              % (paramstuple.nchannels, paramstuple.framerate,
                 paramstuple.sampwidth, paramstuple.nframes))

        with spaudio.open('wo', params=paramstuple, buffersize=1024,
                          callback=(spaudio.OUTPUT_POSITION_CALLBACK | spaudio.OUTPUT_BUFFER_CALLBACK,
                                    myaudiocb, paramstuple.framerate, paramstuple.nframes)) as a:
            b = wf.readframes(paramstuple.nframes)
            nwrite = a.writeraw(b)


if __name__ == '__main__':
    if len(sys.argv) <= 1:
        print('usage: %s filename'
              % os.path.basename(sys.argv[0]), file=sys.stderr)
        quit()

    playfromwav2(sys.argv[1])

Record to a WAV file

rectowav.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import argparse
import wave
import spaudio


def rectowav(filename, samprate, nchannels, sampwidth, duration):
    with wave.open(filename, 'wb') as wf:
        nframes = round(duration * samprate)
        print('nchannels = %d, samprate = %d, sampwidth = %d, nframes = %d'
              % (nchannels, samprate, sampwidth, nframes))

        a = spaudio.SpAudio()

        a.setnchannels(nchannels)
        a.setsamprate(samprate)
        a.setsampwidth(sampwidth)

        a.open('ro')

        b = a.createrawarray(nframes * nchannels)

        nread = a.readraw(b)
        print('nread = %d' % nread)

        a.close()

        wf.setnchannels(nchannels)
        wf.setframerate(samprate)
        wf.setsampwidth(sampwidth)
        wf.setnframes(nframes)

        wf.writeframes(b)
        print('output file: %s' % filename, file=sys.stderr)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Record to a wave file')
    parser.add_argument('filename', help='name of output wave file')
    parser.add_argument('-f', '--samprate', type=int,
                        default=8000, help='sampling rate [Hz]')
    parser.add_argument('-c', '--nchannels', type=int,
                        default=1, help='number of channels')
    parser.add_argument('-w', '--sampwidth', type=int,
                        default=2, help='sample width [byte]')
    parser.add_argument('-d', '--duration', type=float,
                        default=2.0, help='recording duration [s]')
    args = parser.parse_args()

    rectowav(args.filename, args.samprate, args.nchannels,
             args.sampwidth, args.duration)

Record to a WAV file (using with statement; version 0.7.15+)

rectowav2.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.15+ required.

import sys
import argparse
import wave
import spaudio


def rectowav2(filename, samprate, nchannels, sampwidth, duration):
    with wave.open(filename, 'wb') as wf:
        nframes = round(duration * samprate)
        print('nchannels = %d, samprate = %d, sampwidth = %d, nframes = %d'
              % (nchannels, samprate, sampwidth, nframes))

        with spaudio.open('ro', nchannels=nchannels, samprate=samprate,
                          sampbit=(8 * sampwidth)) as a:
            b = a.createrawarray(nframes * nchannels)

            nread = a.readraw(b)
            print('nread = %d' % nread)

            paramstuple = a.getparamstuple(True, nframes)
            wf.setparams(paramstuple)
            wf.writeframes(b)
            print('output file: %s' % filename, file=sys.stderr)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Record to a wave file')
    parser.add_argument('filename', help='name of output wave file')
    parser.add_argument('-f', '--samprate', type=int,
                        default=8000, help='sampling rate [Hz]')
    parser.add_argument('-c', '--nchannels', type=int,
                        default=1, help='number of channels')
    parser.add_argument('-w', '--sampwidth', type=int,
                        default=2, help='sample width [byte]')
    parser.add_argument('-d', '--duration', type=float,
                        default=2.0, help='recording duration [s]')
    args = parser.parse_args()

    rectowav2(args.filename, args.samprate, args.nchannels,
              args.sampwidth, args.duration)

Block read (version 0.7.15+)

blockread.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.15+ required.

import spaudio

blocklen = 8192
nchannels = 2
samprate = 44100
nframes = 88200  # 2.0 [s]

a = spaudio.SpAudio()

a.open('ro', nchannels=nchannels, samprate=samprate)
b = a.createarray(nframes, True)
nloop = ((nframes * nchannels) + blocklen - 1) // blocklen  # ceil

for i in range(nloop):
    nread = a.read(b, offset=(i * blocklen), length=blocklen)
    print('%d: nread = %d' % (i, nread))

a.close()

a.open('wo', nchannels=nchannels, samprate=samprate)

nwrite = a.write(b)
print('nwrite = %d' % nwrite)

a.close()

Block write (version 0.7.15+)

blockwrite.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.15+ required.

import spaudio

blocklen = 8192
nchannels = 2
samprate = 44100
nframes = 88200  # 2.0 [s]

a = spaudio.SpAudio()

a.open('ro', nchannels=nchannels, samprate=samprate)
b = a.createarray(nframes, True)

nread = a.read(b)
print('nread = %d' % nread)

a.close()

a.open('wo', nchannels=nchannels, samprate=samprate)
nloop = ((nframes * nchannels) + blocklen - 1) // blocklen  # ceil

for i in range(nloop):
    nwrite = a.write(b, offset=(i * blocklen), length=blocklen)
    print('%d: write = %d' % (i, nwrite))

a.close()

An example of readframes() and writeframes() (version 0.7.16+)

rwframesexample.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.16+ required.

import spaudio

blocklen = 8192
nchannels = 2
samprate = 44100
nframes = 88200  # 2.0 [s]

a = spaudio.SpAudio()

a.open('ro', nchannels=nchannels, samprate=samprate)

b = a.readframes(nframes, arraytype='array')
print('nread = %d' % len(b))

a.close()

a.open('wo', nchannels=nchannels, samprate=samprate)

nwframes = a.writeframes(b)
print('write frames = %d' % nwframes)

a.close()

spplugin

An example of audioread() (version 0.7.16+)

audioreadexample.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.16+ required.

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

An example of audiowrite() (version 0.7.16+)

audiowriteexample.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.16+ required.

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

An example of audioread() and audiowrite() (version 0.7.16+)

audiorwexample.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.16+ required.

import os
import sys
import spplugin


def audiorwexample(ifilename, ofilename):
    data, samprate, params = spplugin.audioread(ifilename)
    print('nread = %d' % len(data))
    print('samprate = ' + str(samprate) + ', params =\n' + str(params))

    if False:
        nwframes = spplugin.audiowrite(ofilename, data, samprate,
                                       sampbit=params['sampbit'])
    else:
        nwframes = spplugin.audiowrite(ofilename, data, params=params)
    print('write frames = %d' % nwframes)

    data2, samprate2, params2 = spplugin.audioread(ofilename)
    print('reload: nread = %d' % len(data2))
    print('reload: samprate = ' + str(samprate2) + ', params =\n' + str(params2))


if __name__ == '__main__':
    if len(sys.argv) <= 2:
        print('usage: %s ifilename ofilename'
              % os.path.basename(sys.argv[0]), file=sys.stderr)
        quit()

    audiorwexample(sys.argv[1], sys.argv[2])

Plot an audio file contents by plugin

plotfilebyplugin.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import spplugin


def plotfilebyplugin(filename):
    with spplugin.open(filename, 'r') as pf:
        print('input plugin: %s (%s)' % (pf.getpluginid(), pf.getplugindesc()))
        print('plugin version: %d.%d' % pf.getpluginversion())

        nchannels = pf.getnchannels()
        samprate = pf.getsamprate()
        sampbit = pf.getsampbit()
        nframes = pf.getnframes()
        duration = nframes / samprate
        print('nchannels = %d, samprate = %d, sampbit = %d, nframes = %d, duration = %.2f'
              % (nchannels, samprate, sampbit, nframes, duration))

        # In version 0.7.16+, y.resize() can be omitted by channelwise=True.
        # y = pf.createndarray(nframes, True, channelwise=True)
        y = pf.createndarray(nframes, True)
        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])

Play an audio file contents by plugin

playfilebyplugin.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.15+ required.

import os
import sys
import spplugin
import spaudio


def playfilebyplugin(filename):
    with spplugin.open(filename, 'r') as pf:
        print('input plugin: %s (%s)' % (pf.getpluginid(), pf.getplugindesc()))
        print('plugin version: %d.%d' % pf.getpluginversion())

        nchannels = pf.getnchannels()
        samprate = pf.getsamprate()
        sampbit = pf.getsampbit()
        nframes = pf.getnframes()
        print('nchannels = %d, samprate = %d, sampbit = %d, nframes = %d'
              % (nchannels, samprate, sampbit, nframes))

        filetype = pf.getfiletype()
        filedesc = pf.getfiledesc()
        filefilter = pf.getfilefilter()
        if filetype:
            print('filetype = %s %s'
                  % (filetype, '(' + filedesc +
                     ('; ' + filefilter if filefilter else '') + ')' if filedesc else ''))
        songinfo = pf.getsonginfo()
        if songinfo:
            print('songinfo = ' + str(songinfo))

        with spaudio.open('wo', nchannels=nchannels, samprate=samprate,
                          sampbit=sampbit) as a:
            b = a.createarray(nframes, True)
            nread = pf.read(b)
            print('nread = %d' % nread)

            nwrite = a.write(b)
            print('nwrite = %d' % nwrite)


if __name__ == '__main__':
    if len(sys.argv) <= 1:
        print('usage: %s filename'
              % os.path.basename(sys.argv[0]), file=sys.stderr)
        quit()

    playfilebyplugin(sys.argv[1])

Play a raw file contents by plugin

playrawbyplugin.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.15+ required.

import argparse
import spplugin
import spaudio


def playrawbyplugin(filename, samprate, nchannels, sampbit, filetype):
    with spplugin.open(filename, 'r', pluginname='input_raw', samprate=samprate,
                       nchannels=nchannels, sampbit=sampbit, filetype=filetype) as pf:
        print('input plugin: %s (%s)' % (pf.getpluginid(), pf.getplugindesc()))
        print('plugin version: %d.%d' % pf.getpluginversion())

        nchannels = pf.getnchannels()
        samprate = pf.getsamprate()
        sampbit = pf.getsampbit()
        nframes = pf.getnframes()
        print('nchannels = %d, samprate = %d, sampbit = %d, nframes = %d'
              % (nchannels, samprate, sampbit, nframes))

        filetype = pf.getfiletype()
        filedesc = pf.getfiledesc()
        filefilter = pf.getfilefilter()
        if filetype:
            print('filetype = %s %s'
                  % (filetype, '(' + filedesc +
                     ('; ' + filefilter if filefilter else '') + ')' if filedesc else ''))
        songinfo = pf.getsonginfo()
        if songinfo:
            print('songinfo = ' + str(songinfo))

        with spaudio.open('wo', nchannels=nchannels, samprate=samprate,
                          sampbit=sampbit) as a:
            b = pf.readframes(nframes)
            print('nread = %d' % len(b))

            nwframes = a.writeframes(b)
            print('write frames = %d' % nwframes)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Play an audio file including a raw file')
    parser.add_argument('filename', help='name of input file')
    parser.add_argument('-f', '--samprate', type=int,
                        default=8000, help='sampling rate [Hz]')
    parser.add_argument('-c', '--nchannels', type=int,
                        default=1, help='number of channels')
    parser.add_argument('-b', '--sampbit', type=int,
                        default=16, help='bits/sample')
    parser.add_argument('-t', '--filetype', help='file type string')
    args = parser.parse_args()

    playrawbyplugin(args.filename, args.samprate, args.nchannels,
                    args.sampbit, args.filetype)

Read an audio file by plugin and write it

writefrombyplugin.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import aifc
import wave
import sunau
import spplugin


def writefrombyplugin(inputfile, outputfile):
    _, ofileext = os.path.splitext(outputfile)
    if ofileext in ('.wav', '.wave'):
        sndlib = wave
        decodebytes = True
        obigendian_or_signed8bit = False
    elif ofileext == '.au':
        sndlib = sunau
        decodebytes = True
        obigendian_or_signed8bit = True
    elif ofileext in ('.aif', '.aiff', '.aifc', '.afc'):
        sndlib = aifc
        decodebytes = False
        obigendian_or_signed8bit = True
    else:
        raise RuntimeError('output file format is not supported')

    with spplugin.open(inputfile, 'r') as pf:
        print('input plugin: %s (%s)' % (pf.getpluginid(), pf.getplugindesc()))
        print('plugin version: %d.%d' % pf.getpluginversion())

        params = pf.getparams()
        print('nchannels = %d, samprate = %d, sampbit = %d, nframes = %d'
              % (params['nchannels'], params['samprate'], params['sampbit'], params['nframes']))

        if params['filetype']:
            print('filetype = %s %s'
                  % (params['filetype'], '(' + params['filedesc'] +
                     ('; ' + params['filefilter'] if params['filefilter'] else '') +
                     ')' if params['filedesc'] else ''))
        if params['songinfo']:
            print('songinfo = ' + str(params['songinfo']))

        b = pf.createrawarray(params['nframes'], True)
        nread = pf.readraw(b)
        print('nread = %d' % nread)

        paramstuple = pf.getparamstuple(decodebytes)

        with sndlib.open(outputfile, 'wb') as sf:
            sf.setparams(paramstuple)
            y = pf.copyarray2raw(b, paramstuple.sampwidth, bigendian_or_signed8bit=obigendian_or_signed8bit)
            sf.writeframes(y)
            print('output file: %s' % outputfile, file=sys.stderr)


if __name__ == '__main__':
    if len(sys.argv) <= 2:
        print('usage: %s inputfile outputfile'
              % os.path.basename(sys.argv[0]), file=sys.stderr)
        quit()

    writefrombyplugin(sys.argv[1], sys.argv[2])

Read an audio file and write it by plugin

writetobyplugin.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import aifc
import wave
import sunau
import spplugin


def writefrombyplugin(inputfile, outputfile):
    _, ifileext = os.path.splitext(inputfile)
    if ifileext in ('.wav', '.wave'):
        sndlib = wave
        decodebytes = True
        ibigendian_or_signed8bit = False
    elif ifileext == '.au':
        sndlib = sunau
        decodebytes = True
        ibigendian_or_signed8bit = True
    elif ifileext in ('.aif', '.aiff', '.aifc', '.afc'):
        sndlib = aifc
        decodebytes = False
        ibigendian_or_signed8bit = True
    else:
        raise RuntimeError('input file format is not supported')

    with sndlib.open(inputfile, 'rb') as sf:
        params = sf.getparams()

        print('nchannels = %d, framerate = %d, sampwidth = %d, nframes = %d'
              % (params.nchannels, params.framerate, params.sampwidth, params.nframes))

        if params.comptype:
            print('comptype = %s %s'
                  % (params.comptype, '(' + params.compname +
                     ')' if params.compname else ''))

        y = sf.readframes(params.nframes)

        with spplugin.open(outputfile, 'w', params=params) as pf:
            print('output plugin: %s (%s)' % (pf.getpluginid(), pf.getplugindesc()))
            print('plugin version: %d.%d' % pf.getpluginversion())

            b = pf.copyraw2array(y, params.sampwidth, bigendian_or_signed8bit=ibigendian_or_signed8bit)
            nwrite = pf.writeraw(b)
            print('nwrite = %d' % nwrite)

            print('output file: %s' % outputfile, file=sys.stderr)


if __name__ == '__main__':
    if len(sys.argv) <= 2:
        print('usage: %s inputfile outputfile'
              % os.path.basename(sys.argv[0]), file=sys.stderr)
        quit()

    writefrombyplugin(sys.argv[1], sys.argv[2])

Convert an audio file by plugin

convbyplugin.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import spplugin


def convbyplugin(inputfile, outputfile):
    with spplugin.open(inputfile, 'r') as pf:
        print('input plugin: %s (%s)' % (pf.getpluginid(), pf.getplugindesc()))
        print('plugin version: %d.%d' % pf.getpluginversion())

        params = pf.getparams()
        print('nchannels = %d, samprate = %d, sampbit = %d, nframes = %d'
              % (params['nchannels'], params['samprate'], params['sampbit'],
                 params['nframes']))

        if params['filetype']:
            print('filetype = %s %s'
                  % (params['filetype'], '(' + params['filedesc'] +
                     ('; ' + params['filefilter'] if params['filefilter'] else '') +
                     ')' if params['filedesc'] else ''))
        if params['songinfo']:
            print('songinfo = ' + str(params['songinfo']))

        b = pf.createrawarray(params['nframes'], True)
        nread = pf.readraw(b)
        print('nread = %d' % nread)

        with spplugin.open(outputfile, 'w', params=params) as pf:
            print('output plugin: %s (%s)' % (pf.getpluginid(), pf.getplugindesc()))
            print('plugin version: %d.%d' % pf.getpluginversion())

            nwrite = pf.writeraw(b)
            print('nwrite = %d' % nwrite)

            print('output file: %s' % outputfile, file=sys.stderr)


if __name__ == '__main__':
    if len(sys.argv) <= 2:
        print('usage: %s inputfile outputfile'
              % os.path.basename(sys.argv[0]), file=sys.stderr)
        quit()

    convbyplugin(sys.argv[1], sys.argv[2])