Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a wav file using sounddevice and numpy in python3

I would like to record a tone with sounddevice i created numpy and write it into a wav file. here is the code:

import numpy 
import sounddevice as sd
import soundfile as sf
import sys

duration = 3
amplitude = 0.3
sampling_frequency = 44100

time = numpy.arange(int(numpy.ceil(duration * sampling_frequency))) /   sampling_frequency

frequency1 = 500
tone1 = amplitude * numpy.sin(2* numpy.pi * frequency1 * time)

frequency2 = 700
tone2 = amplitude * numpy.sin(2* numpy.pi * frequency1 * time)
frequency3 = 1500
tone3 = amplitude * numpy.sin(3* numpy.pi * frequency1 * time)
frequency4 = 400
tone4 = amplitude * numpy.sin(4* numpy.pi * frequency1 * time)

result = tone1
result2 = tone2
result3 = tone3
result4 = tone4

sd.play(result + result2 + result3 + result4, sampling_frequency)

filename = 'output.wav'

mydata = sd.rec(int(result + result2 + result3 + result4),sampling_frequency,channels=2, blocking=True)
sf.write(filename, mydata, sampling_frequency)

I get this error: only length-1 arrays can be converted to Python scalars What's wrong with the code? I'm a newbie with python

like image 945
H.e Avatar asked Mar 14 '26 04:03

H.e


1 Answers

Your second-to-last line is

mydata = sd.rec(int(result + result2 + result3 + result4),sampling_frequency,channels=2, blocking=True)

Where you try to cast the sum of the result1 etc variables to an integer. However, they are actually numpy arrays, since time is an array. You cannot convert an array into a single integer, since it has multiple values. I'm not sure why you are trying to do that, you probably just want to remove the int(), and change it to

mydata = sd.rec(result + result2 + result3 + result4, sampling_frequency, channels=2, blocking=True)
like image 195
Coolness Avatar answered Mar 15 '26 20:03

Coolness



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!