Examples¶
spaudio¶
Fullduplex I/O¶
#!/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+)¶
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.5+ 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)¶
#!/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)¶
#!/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)¶
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import spaudio
import numpy as np
import matplotlib.pyplot as plt
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 raw ndarray version)¶
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import spaudio
import numpy as np
import matplotlib.pyplot as plt
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¶
#!/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+)¶
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.5+ 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¶
#!/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+)¶
#!/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¶
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
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 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+)¶
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.5+ required.
import os
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 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)
spplugin¶
Plot an Audio File Contents by Plugin¶
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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:
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))
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¶
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 0.7.5+ 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])
Read an Audio File by Plugin and Write it¶
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import aifc
import wave
import sunau
import spplugin
def writefrombyplugin(inputfile, outputfile):
ofilebody, ofileext = os.path.splitext(outputfile)
if ofileext == '.wav' or ofileext == '.wave':
sndlib = wave
decodebytes = True
obigendian_or_signed8bit = False
elif ofileext == '.au':
sndlib = sunau
decodebytes = True
obigendian_or_signed8bit = True
elif (ofileext == '.aif' or ofileext == '.aiff' or
ofileext == '.aifc' or ofileext == '.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['length']))
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['length'], 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¶
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import aifc
import wave
import sunau
import spplugin
def writefrombyplugin(inputfile, outputfile):
ifilebody, ifileext = os.path.splitext(inputfile)
if ifileext == '.wav' or ifileext == '.wave':
sndlib = wave
decodebytes = True
ibigendian_or_signed8bit = False
elif ifileext == '.au':
sndlib = sunau
decodebytes = True
ibigendian_or_signed8bit = True
elif (ifileext == '.aif' or ifileext == '.aiff' or
ifileext == '.aifc' or ifileext == '.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¶
#!/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['length']))
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['length'], 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])