# Sound, how is it done?

This post is a wiki. Anyone with karma >750 is welcome to improve it.

Im working on an interactive piece using an alternate form of the doppler effect and I would appreciate some help in making it play sound. Thank you

import wave

class SoundFile:
def  __init__(self, signal,lab=''):
self.file = wave.open('./test' + lab + '.wav', 'wb')
self.signal = signal
self.sr = 44100

def write(self):
self.file.setparams((1, 2, self.sr, 44100*4, 'NONE', 'noncompressed'))
self.file.writeframes(self.signal)
self.file.close()

mypi = float(pi)
from math import sin
var('x')

@interact
def sinsound(f = slider(16,16000,1,5120)):
v = 340.29
html('$y = f*(((v)+ tan(x))/((v)+sin(x))))$')
y = f*((v+tan(x))/(v+sin(x)))
hz1 = y
s2 = [sin(hz1*x*mypi*2) for x in srange(0,4,1/44100.0)]
s2m = max(s2)
s2f = [16384*x/s2m for x in s2]
s2str = ''.join(wave.struct.pack('h',x) for x in s2f)
lab="%1.2f"%float(f)
f = SoundFile(s2str,lab=lab)
f.write()
pnum = 1500+int(500/f)
show(list_plot(s2[0:pnum],plotjoined=True))
html('<embed src="cell://test'+ lab +'.wav" width="200" height="100"></embed>')

edit retag close merge delete

1

Hi. It is not clear at all what your code shoud do !! The variable **y** seems to be a function of **x** but is used as a float number. The parameter **f** has the same name as the **SoundFile** object... Anyway, as such because you use the function **sin** from **math** I get an error because you can not evaluate it on a symbolic variable.

( 2013-05-04 18:29:36 +0200 )edit

You may also find the discussion [here](https://groups.google.com/forum/?fromgroups=#!topic/sage-devel/3-Y1RUFkq14) interesting, as well as [this ticket](http://trac.sagemath.org/sage_trac/ticket/7668).

( 2013-05-07 22:46:50 +0200 )edit

Sort by ยป oldest newest most voted

This post is a wiki. Anyone with karma >750 is welcome to improve it.

Building on vdelecroix's comments, and slightly amending your code, the following works for me.

import wave

rdf_two_pi = RDF(2*pi)

class SoundFile:
def  __init__(self,signal,lab=''):
self.file = wave.open('./test' + lab + '.wav', 'wb')
self.signal = signal
self.sr = 44100
def write(self):
self.file.setparams((1, 2, self.sr, 44100*4, 'NONE', 'noncompressed'))
self.file.writeframes(self.signal)
self.file.close()

@interact
def sinsound(f=slider(16,16000,1,5120)):
v = 340.29
html(r'$$y = f \, \frac{v+\tan x}{v+\sin x}$$')
def y(x):
x = RDF(x)
return f*((v+tan(x))/(v+sin(x)))
s2 = [sin(y(t)*t*rdf_two_pi) for t in srange(0,4,1/44100.0)]
s2m = max(s2)
s2f = [int(16384*t/s2m) for t in s2]
s2str = ''.join(wave.struct.pack('h',t) for t in s2f)
lab="%1.2f"%float(f)
sf = SoundFile(s2str,lab=lab)
sf.write()
pnum = 1500+int(500/f)
show(list_plot(s2[0:pnum],plotjoined=True))
html('<embed src="cell://test'+ lab +'.wav" width="200" height="100"></embed>')

more