将蜂鸣声保存在 .wav 文件中

Save beep sound in a .wav file

我在 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('\r\a{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('\r\a{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)

问题中的代码只提供了两个参数。

3 个参数是:

  1. 文件(str 或 int 或 file-like 对象)
  2. 数据(array_like)
  3. 采样率(整数)

samplerate 不见了。

根据给定的文档,这有效:

## 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('\r\a{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_programming\python\tests\Beep.wav'
with sf.SoundFile(file, 'w', 44100, 2, 'PCM_24') as f:
    f.write(np.random.randn(10, 2))