如何将 wav 写入 tfrecord 然后读回

How to write a wav to a tfrecord and then read it back

我正在尝试将编码的 wav 写入 tfrecord,然后将其读回。我知道我可以将 wav 写成普通张量,但我正在尝试保存 space.

我想做类似下面的事情,但不确定如何填写省略号。特别是,我不知道我应该保存为 int64 特征还是字节特征。

def wav_feature(wav):
    value = tf.audio.encode_wav(wav, 44100)
    return tf.train.Feature(...)

example = tf.train.Example(features=tf.train.Features(feature={
    'foo': wav_feature(wav),
}))

with tf.io.TFRecordWriter(outpath) as writer:
    writer.write(example.SerializeToString())

# In parser

features = tf.io.parse_single_example(
            serialized=proto,
            features={'foo': tf.io.FixedLenFeature([], ...)})

decoded, sr = tf.audio.decode_wav(features['foo'])

看起来像encode_wavreturns a string tensor,所以最好使用字节特征:

def _bytes_feature(value):                                                      
  """Returns a bytes_list from a string / byte."""                              
  if isinstance(value, type(tf.constant(0))):                                   
    value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))         

# Convert to a string tensor.
wav_encoded = tf.audio.encode_wav(wav, 44100)

feature = {'foo': _bytes_feature(wav_encoded)}         
example = tf.train.Example(features=tf.train.Features(feature=feature))      

然后,在解析器中:

features = tf.io.parse_single_example(
        example.SerializeToString(),                 
        features={'foo': tf.io.FixedLenFeature([], tf.string)})               
# wav_encoded will be a string tensor. 
wav_encoded = features['foo']

_bytes_feature 的定义是 here