Created
May 19, 2012 00:19
-
-
Save automata/2728285 to your computer and use it in GitHub Desktop.
tutorial web audio api: tocando arquivo em tempo
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
// criamos um "contexto sonoro", objeto que permite acessar a placa de áudio | |
var context = new webkitAudioContext(); | |
// carregaremos um buffer de áudio nessa variável | |
var som = null; | |
function carregaSom(url) { | |
// cria uma requisição assíncrona para carregar o arquivo de áudio de uma url | |
var request = new XMLHttpRequest(); | |
request.open('GET', url, true); | |
// carregaremos um vetor de dados float, não texto | |
request.responseType = 'arraybuffer'; | |
// decodificamos o arquivo de áudio, quando o carregamos | |
request.onload = function() { | |
context.decodeAudioData(request.response, function(buffer) { | |
som = buffer; | |
}); | |
//snare = context.createBuffer(request.response, false); | |
} | |
// exibimos uma mensagem de erro se não conseguirmos carregar | |
request.onerror = function() { | |
alert('Error while loading'); | |
} | |
// enviamos a requisição | |
request.send(); | |
} | |
// carregamos o som | |
carregaSom('./samples/kick.wav'); | |
// toca um som que carregamos com carregaSom() | |
function tocaSom(tempo) { | |
// cria um buffer (espaço na memória, para podermos tocar) | |
var source = context.createBufferSource(); | |
// associa o arquivo que carregamos a este buffer | |
source.buffer = som; | |
// conecta o buffer ao destino à saída de som | |
source.connect(context.destination); | |
// toca o buffer no tempo (em segundos depois de context.currentTime) | |
source.noteOn(tempo); | |
} | |
function tocaTudo() { | |
// context.currentTime possui o tempo atual em segundos, sempre crescente | |
var inicio = context.currentTime; | |
// batidas por minuto | |
var bpm = 80; | |
// tempo de cada nota (a cada 60 segundos temos 80 batidas) | |
var tempoNota = (60 / bpm) / 2; | |
// toca 4 compassos | |
for (var compasso = 0; compasso < 4; compasso++) { | |
var tempo = inicio + compasso * 8 * tempoNota; | |
// toca nos tempos 1 e 3 | |
tocaSom(tempo); | |
tocaSom(tempo + 2 * tempoNota); | |
} | |
} | |
// para usar, chame tocaTudo() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment