简体   繁体   English

如何将 numpy 数组波形转换为类似 wav 文件的对象?

[英]How to convert a numpy array waveform into a wav file-like object?

I want to convert a numpy array waveform into a wav-like object so that I can upload it to S3 without having to save the waveform to file locally.我想将 numpy 数组波形转换为类似 wav 的对象,以便我可以将其上传到 S3,而无需将波形保存到本地文件。 Imagine I have a numpy array waveform, y ,想象一下,我有一个 numpy 数组波形y

y, sr = librosa.load('something.wav', sr = 44100)

How can I convert this numpy array, y into a wav file-like object to upload to S3 using boto3 's upload_fileobj method?如何使用boto3upload_fileobj方法将此 numpy 数组y转换为类似 wav 文件的对象以上传到 S3?

According to the boto3 docs, the file-like object must have the properties:根据boto3文档,类文件对象必须具有以下属性:

A file-like object to upload.要上传的类似文件的对象。 At a minimum, it must implement the read method, and must return bytes.至少,它必须实现 read 方法,并且必须返回字节。

This is how I would like to upload the file-like object:这就是我想上传类似文件的对象的方式:

import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')

# with open('filename', 'rb') as data:
#    bucket.upload_fileobj(data, 'mykey')
bucket.upload_fileobj(wav_object, 'something.wav')

TLDR: TLDR:

I want a function that converts a numpy array into a wav-like object that implements the read method and returns bytes.我想要一个将 numpy 数组转换为类似 wav 的对象的函数,该对象实现 read 方法并返回字节。

You can try like this:你可以这样尝试:

import io 
from scipy.io.wavfile import write
import boto3

bytes_wav = bytes()
wav_object = io.BytesIO(bytes_wav)
write(wav_object, sr, y) # y is your numpy array


s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')

bucket.upload_fileobj(wav_object, 'something.wav')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将PDF转换/写入为RAM,就像文件一样,以便进一步使用它 - Convert/Write PDF to RAM as file-like object for further working with it 如何在 Python3 中将异步生成器 stream 转换为类文件 object? - How to convert async generator stream into a file-like object in Python3? 如何将形状 (h,w,c) 的 ndarray 转换为类似文件的对象 - How to convert ndarray of shape (h,w,c) to file-like object 如何判断我是否有类似文件的对象? - How can I tell if I have a file-like object? tornado:如何创建写入RequestHandler的类文件对象? - tornado: How to create file-like object that writes to a RequestHandler? 如何从迭代器创建 Python 文件,如 Object - How To Create a Python file-like Object from an Iterator 如何使用自定义类文件对象作为子进程 stdout/stderr? - How to use a custom file-like object as subprocess stdout/stderr? 如何将 numpy 数组中的 32 位 wav 文件转换为 24 位 wav 文件? - How to convert 32bit wav file in a numpy array to a 24bit wav file? 如何在 Python 3 中将演示文稿保存到类似文件的对象 - How to save a presentation to a file-like object in Python 3 如何使用 json 模块将 python 对象转换为 (json) 嵌套 dict,而不创建类似文件的对象? - How do I convert a python object to (json) nested dict using the json module, without making a file-like object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM