我想用sounddevice录制一个音调,我创建numpy并将其写入wav文件。这是代码:
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)
我收到此错误:只有length-1数组可以转换为Python标量 代码有什么问题?我是python的新手
答案 0 :(得分:0)
你的倒数第二行是
mydata = sd.rec(int(result + result2 + result3 + result4),sampling_frequency,channels=2, blocking=True)
您尝试将result1
等变量的总和转换为整数。但是,它们实际上是numpy
数组,因为time
是一个数组。您无法将数组转换为单个整数,因为它具有多个值。我不确定你为什么要这样做,你可能只想删除int()
,然后将其更改为
mydata = sd.rec(result + result2 + result3 + result4, sampling_frequency, channels=2, blocking=True)
答案 1 :(得分:0)
sd.rec()
用于记录来自声音设备的声音并输出阵列。它期望记录应该持续多长时间的整数。这就是为什么它抛出"TypeError: 'list' object cannot be interpreted as an integer"
的原因。
https://python-sounddevice.readthedocs.io/en/0.3.7/#recording
您不必记录数据,因为您已经有了数据(您的结果变量)。所以你应该更换
mydata = sd.rec(int(result + result2 + result3 + result4),sampling_frequency,channels=2, blocking=True)
使用
mydata = result + result2 + result3 + result4