将嘟嘟声保存在.wav文件中



我在Python中生成了一个嘟嘟声,持续5毫秒,每1秒重复一次,持续10秒。

代码如下:

## Import modules
import time
import sys
import winsound
import soundfile as sf 

## Set frequency and duration of beep sound
frequency = 37  
duration  =  5   # duration of beep sound is 5ms
for i in range(1,10):                                   # create beep sound for 10s
## Create beep sound for 5 ms, after every 1 s
sys.stdout.write('ra{i}'.format(i=i))
sys.stdout.flush()
winsound.Beep(frequency, duration)
time.sleep(1)                                       # Repeat beep sound after 1s

现在,我想把这个模式保存在.wav文件中。因此,我更改了代码:

## Import modules
import time
import sys
import winsound
import soundfile as sf 

## Set frequency and duration of beep sound
frequency = 37  
duration  =  5    # duration of beep sound is 5ms 
for i in range(1,10):  # create beep spund for 10 s
## Create beep sound for 5 ms, after every 1 s
sys.stdout.write('ra{i}'.format(i=i))
sys.stdout.flush()
winsound.Beep(frequency, duration)
time.sleep(1)

## Save the beep spund as a .wav file
sf.write("Beep.wav", winsound.Beep(frequency, duration))

然而,我总是犯错误。

有人能告诉我如何将其保存在.wav文件中吗?

错误如下:

write() missing 1 required positional argument: 'samplerate'

从这里的文档:https://pysoundfile.readthedocs.io/en/latest/

我们可以看到,该函数需要3个参数:

sf.write('new_file.flac', data, samplerate)

问题中的代码只提供了两个论点。

三个论点是:

  1. 文件(str或int或类似文件的对象(
  2. 数据(类数组(
  3. 采样率(int(

Itsamplerate丢失。

有了给定的文档,这就起作用了:

## Import modules
import time
import sys
import numpy as np
import winsound
import soundfile as sf 

## Set frequency and duration of beep sound
frequency = 37  
duration  =  5    # duration of beep sound is 5ms 
for i in range(1,10):  # create beep spund for 10 s
## Create beep sound for 5 ms, after every 1 s
sys.stdout.write('ra{i}'.format(i=i))
sys.stdout.flush()
winsound.Beep(frequency, duration)
time.sleep(1)

## Save the beep spund as a .wav file
file = 'G:\My Drive\darren\02_programmingpython\tests\Beep.wav'
with sf.SoundFile(file, 'w', 44100, 2, 'PCM_24') as f:
f.write(np.random.randn(10, 2))

相关内容

最新更新