Playing a sound from a wave form stored in an array

时光毁灭记忆、已成空白 提交于 2019-11-29 07:17:27

You should use a library. Writing it all in pure python could be many thousands of lines of code, to interface with the audio hardware!

With a library, e.g. audiere, it will be as simple as this:

import audiere
ds = audiere.open_device()
os = ds.open_array(input_array, 44100)
os.play()

There's also pyglet, pygame, and many others..

To play sound given array input_array of 16 bit samples. This is modified example from pyadio documentation page

import pyaudio

# instantiate PyAudio (1)
p = pyaudio.PyAudio()

# open stream (2), 2 is size in bytes of int16
stream = p.open(format=p.get_format_from_width(2),
                channels=1,
                rate=44100,
                output=True)

# play stream (3), blocking call
stream.write(input_array)

# stop stream (4)
stream.stop_stream()
stream.close()

# close PyAudio (5)
p.terminate()

or use the sounddevice module. Install using pip install sounddevice, but you need this first: sudo apt-get install libportaudio2

absolute basic:

import numpy as np
import sounddevice as sd

sd.play(myarray) 
#may need to be normalised like in below example
#myarray must be a numpy array. If not, convert with np.array(myarray)

A few more options:

import numpy as np
import sounddevice as sd

#variables
samplfreq = 100   #the sampling frequency of your data (mine=100Hz, yours=44100)
factor = 10       #incr./decr frequency (speed up / slow down by a factor) (normal speed = 1)

#data
print('..interpolating data')
arr = myarray

#normalise the data to between -1 and 1. If your data wasn't/isn't normalised it will be very noisy when played here
sd.play( arr / np.max(np.abs(arr)), samplfreq*factor)

I think you may look this list http://wiki.python.org/moin/PythonInMusic It list many useful tools for working with sound.

Here's a snippet of code taken from this stackoverflow answer, with an added example to play a numpy array (scipy loaded sound file):

from wave import open as waveOpen
from ossaudiodev import open as ossOpen
from ossaudiodev import AFMT_S16_NE
import numpy as np
from scipy.io import wavfile

# from https://stackoverflow.com/questions/307305/play-a-sound-with-python/311634#311634
# run this: sudo modprobe snd-pcm-oss
s = waveOpen('example.wav','rb')
(nc,sw,fr,nf,comptype, compname) = s.getparams( )
dsp = ossOpen('/dev/dsp','w')

print(nc,sw,fr,nf,comptype, compname)

_, snp = wavfile.read('example.wav')
print(snp)

dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)
s.close()

dsp.write(snp.tobytes())
dsp.write(data)
dsp.close()

Basically you can just call the tobytes() method; the returned bytearray then can be played.

P.S. this method is supa fast

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!