【问题标题】:How to read Ogg or MP3 audio files in a TensorFlow graph?如何在 TensorFlow 图中读取 Ogg 或 MP3 音频文件?
【发布时间】:2017-04-27 20:07:13
【问题描述】:

我在 TensorFlow 中见过像 tf.image.decode_png 这样的图像解码器,但是如何读取音频文件(WAV、Ogg、MP3 等)?没有TFRecord可以吗?

例如类似this:

filename_queue = tf.train.string_input_producer(['my-audio.ogg'])
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
my_audio = tf.audio.decode_ogg(value)

【问题讨论】:

    标签: tensorflow audio ffmpeg


    【解决方案1】:

    对于最新版本的 tensorflow,所有与音频相关的实用程序都已移动/添加到 tensorflow_io (here)。安装运行pip install tensorflow.io

    import tensorflow_io as tfio
    import tensorflow as tf
    
    fp = 'path/to/mp3'
    audio  = tfio.audio.decode_mp3(tf.io.read_file(fp))
    

    【讨论】:

      【解决方案2】:

      最近在tensorflow_iohere)中添加了这样的功能。 你可以这样使用它:

      content = tf.io.read_file(path)
      audio = tfio.experimental.audio.decode_ogg(content)
      

      【讨论】:

        【解决方案3】:

        很遗憾,TensorFlow 2.x 不支持来自 @sygi 的答案。另一种解决方案是使用一些外部库(例如pydublibrosa)来实现mp3 解码步骤,并通过使用tf.py_function 将其集成到管道中。所以你可以按照以下方式做一些事情:

        from pydub import AudioSegment
        import tensorflow as tf
        
        dataset = tf.data.Dataset.list_files('path/to/mp3s/*')
        
        def decode_mp3(mp3_path):
            mp3_path = mp3_path.numpy().decode("utf-8")
            mp3_audio = AudioSegment.from_file(mp3_path, format="mp3")
            return mp3_audio.get_array_of_samples()
        
        dataset = dataset.map(lambda path:
            tf.py_function(func=decode_mp3, inp=[path], Tout=tf.float32))
        
        for features in dataset.take(3):
            data = features.numpy()
            plt.plot(data)
            plt.show()
        

        【讨论】:

          【解决方案4】:

          是的,有特殊的解码器,在包tensorflow.contrib.ffmpeg 中。要使用它,你需要先安装ffmpeg

          例子:

          audio_binary = tf.read_file('song.mp3')
          waveform = tf.contrib.ffmpeg.decode_audio(audio_binary, file_format='mp3', samples_per_second=44100, channel_count=2)
          

          【讨论】:

          • tf.contrib ffmpeg 在 Windows 中不可用,我通过 conda 安装了 ffmpeg,但它根本不起作用。tf github issue posted on here
          • 太好了!在TensorFlow 1.10.0中需要传递channel_count参数,否则会抛出如下错误:ValueError: Tried to convert 'channel_count' to a tensor and failed. Error: None values not supported.
          猜你喜欢
          • 1970-01-01
          • 2020-06-19
          • 1970-01-01
          • 2012-02-10
          • 1970-01-01
          • 2013-05-07
          • 1970-01-01
          • 1970-01-01
          • 2015-11-08
          相关资源
          最近更新 更多