1

To render image in HTML from numpy array, I can do

def numpy_to_b64(array):
    im_pil = Image.fromarray(array)
    buff = BytesIO()
    im_pil.save(buff, format="png")
    im_b64 = base64.b64encode(buff.getvalue()).decode("utf-8")

    return im_b64

and use img tag

array_b64 = numpy_to_b64(array)
html.Img(src='data:image/png;base64,{}'.format(array_b64))

I wonder if there is a similar approach for audio, or how can I convert a 1-D numpy array which represents audio waveform to a format that can be put in audio tag?

Francis
  • 6,416
  • 5
  • 24
  • 32

1 Answers1

0

Not raw waveform data, since the browser has no way of interpreting that (it wouldn't know the sampling rate, etc.). You need to convert the audio data to e.g. OGG format, which is supported by HTML5. A library like pydub might be the easiest way to accomplish that.

Jussi Nurminen
  • 2,257
  • 1
  • 9
  • 16
  • Thanks, I am looking into `pydub` and working on it. Basically, I get an `AudioSegment` of the array by `audio_seg = AudioSegment(array.tobytes(), frame_rate=22050, sample_width=array.dtype.itemsize, channels=1)` and `audio_seg.export('test.ogg', format='ogg', codec='libvorbis')`. But is there a way to save it in a buffer instead of exporting a file in the disk, just as what is done for the image (`im_pil.save(buff, format="png")`)? – Francis Apr 18 '19 at 12:33