Created
January 30, 2023 21:23
-
-
Save kush-agra/711460317efea91a939ce6d4df039242 to your computer and use it in GitHub Desktop.
Generate vibration from audio file
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
function turnMusicIntoVibrate(audioUrl) { | |
// Create an audio context | |
const audioContext = new AudioContext(); | |
// Create an analyser node | |
const analyser = audioContext.createAnalyser(); | |
analyser.fftSize = 8192; | |
// Load the audio file using fetch | |
fetch(audioUrl) | |
.then(response => response.arrayBuffer()) | |
.then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer)) | |
.then(audioBuffer => { | |
// Create a source node from the audio buffer | |
const source = audioContext.createBufferSource(); | |
source.buffer = audioBuffer; | |
// Connect the source node to the analyser node | |
source.connect(analyser); | |
// Connect the analyser node to the destination | |
analyser.connect(audioContext.destination); | |
// Start the audio playback | |
source.start(); | |
// Add an ended event listener to the source node | |
source.onended = function() { | |
// Get the frequency data from the analyser node | |
const frequencyData = new Uint8Array(analyser.frequencyBinCount); | |
// Use the Navigator.vibrate() method to play the vibrate pattern | |
navigator.vibrate(frequencyData); | |
}; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment