Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

python - Playing a sound from a wave form stored in an array

I'm currently experimenting with generating sounds in Python, and I'm curious how I can take a n array representing a waveform (with a sample rate of 44100 hz), and play it. I'm looking for pure Python here, rather than relying on a library that supports more than just .wav format.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...