audio.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. import IPython.display
  2. import numpy as np
  3. import json
  4. def Audio(audio: np.ndarray, rate: int):
  5. """
  6. Use instead of IPython.display.Audio as a workaround for VS Code.
  7. `audio` is an array with shape (channels, samples) or just (samples,) for mono.
  8. """
  9. if np.ndim(audio) == 1:
  10. channels = [audio.tolist()]
  11. else:
  12. channels = audio.tolist()
  13. return IPython.display.HTML("""
  14. <script>
  15. if (!window.audioContext) {
  16. window.audioContext = new AudioContext();
  17. window.playAudio = function(audioChannels, sr) {
  18. const buffer = audioContext.createBuffer(audioChannels.length, audioChannels[0].length, sr);
  19. for (let [channel, data] of audioChannels.entries()) {
  20. buffer.copyToChannel(Float32Array.from(data), channel);
  21. }
  22. const source = audioContext.createBufferSource();
  23. source.buffer = buffer;
  24. source.connect(audioContext.destination);
  25. source.start();
  26. }
  27. }
  28. </script>
  29. <button onclick="playAudio(%s, %s)" style="padding: 10px">Play</button>
  30. """ % (json.dumps(channels), rate))