问题描述
是否可以使用 Python 或 Javascript 使用 Zapier Code Step 获取音频文件的持续时间?
我已将文件上传到谷歌驱动器,现在我需要文件的持续时间。如果谷歌驱动器文件无法做到这一点。作为替代方案,我可以使用 DropBox 或 Amazon AWS。
我已经尝试过 Zapier 代码步骤(Python):
import wave
import contextlib
fname = input.get('fileurl')
with contextlib.closing(wave.open(fname,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
output = print(duration)
但这行不通。我收到错误消息:
Traceback (most recent call last):
File "<string>",line 11,in the_function
File "/var/lang/lib/python3.7/wave.py",line 510,in open
return Wave_read(f)
File "/var/lang/lib/python3.7/wave.py",line 164,in
解决方法
这是个好问题!我以为这是不可能的,但事实证明确实如此。您的代码无法运行,因为 fileurl
不是文件名,因此库崩溃了(不幸的是,没有出现有用的错误)。
诀窍是 wave.open
需要一个文件名或类似文件的对象。 Code by Zapier
不能真正使用文件系统,但我们可以创建一个内存中的“文件”,我们可以将其输入 wave
。
试试这个:
import wave
from io import BytesIO
# I pulled a file from
# https://file-examples.com/index.php/sample-audio-files/sample-wav-download/
# but you can use input_data['file_url'] or something instead
file_url = 'https://file-examples-com.github.io/uploads/2017/11/file_example_WAV_1MG.wav'
wave_resp = requests.get(file_url)
wav_file = BytesIO(wave_resp.content)
with wave.open(wav_file) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
return {'duration': duration}
对于那个测试文件,我得到了 duration
的 33.529625
- 我的浏览器说它有大约 33 秒长,所以看起来是正确的!