Last active
August 22, 2022 21:46
-
-
Save naotokui/efa261ab444ada29162c420438ce23e4 to your computer and use it in GitHub Desktop.
play audio on Visual Studio Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# from vscode_audio import * | |
# Audio(audio_numpy_array, sr=SR) | |
import IPython.display | |
import numpy as np | |
import json | |
def Audio(audio: np.ndarray, sr: int): | |
""" | |
Use instead of IPython.display.Audio as a workaround for VS Code. | |
`audio` is an array with shape (channels, samples) or just (samples,) for mono. | |
""" | |
if np.ndim(audio) == 1: | |
channels = [audio.tolist()] | |
else: | |
channels = audio.tolist() | |
return IPython.display.HTML(""" | |
<script> | |
if (!window.audioContext) { | |
window.audioContext = new AudioContext(); | |
window.playAudio = function(audioChannels, sr) { | |
const buffer = audioContext.createBuffer(audioChannels.length, audioChannels[0].length, sr); | |
for (let [channel, data] of audioChannels.entries()) { | |
buffer.copyToChannel(Float32Array.from(data), channel); | |
} | |
const source = audioContext.createBufferSource(); | |
source.buffer = buffer; | |
source.connect(audioContext.destination); | |
source.start(); | |
} | |
} | |
</script> | |
<button onclick="playAudio(%s, %s)">Play</button> | |
""" % (json.dumps(channels), sr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment