Created
May 4, 2021 14:54
-
-
Save suzuki0keiichi/d7d390f075c533ad93c540572acb1aa4 to your computer and use it in GitHub Desktop.
何故か6倍で丁度いい音がなってしまう
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
<html> | |
<head> | |
<meta http-equiv="origin-trial" | |
content="___"/> | |
</head> | |
<body> | |
<audio id="audio"></audio> | |
<button onclick="record()">record</button> | |
<button onclick="play()">play</button> | |
</body> | |
<script> | |
const audio = document.querySelector("#audio") | |
let buf = []; | |
async function play() { | |
const audioCtx = new AudioContext({sampleRate: 44100}); | |
let audioTime = audioCtx.currentTime; | |
const audioDecoder = new AudioDecoder({ | |
output: async function (audioFrame) { | |
const source = audioCtx.createBufferSource(); | |
source.buffer = audioFrame.buffer; | |
source.connect(audioCtx.destination); | |
source.start(audioTime, 0, audioFrame.buffer.duration); | |
audioTime += audioFrame.buffer.duration / 6; // なぜ6倍で丁度いいんだ、、 | |
}, | |
error: function () { | |
console.error(arguments); | |
}, | |
}); | |
audioDecoder.configure({ | |
codec: "opus", | |
numberOfChannels: 1, | |
sampleRate: 44100, | |
}); | |
for (let i in buf) { | |
await audioDecoder.decode(buf[i]); | |
} | |
} | |
async function record() { | |
const localStream = await navigator.mediaDevices | |
.getUserMedia({video: false, audio: true}) | |
.catch((err) => { | |
throw err; | |
}); | |
audio.srcObject = localStream; | |
const [audioTrack] = audio.srcObject.getAudioTracks(); | |
const audioEncoder = new AudioEncoder({ | |
output: function (chunk) { | |
buf.push(chunk); | |
}, | |
error: function () { | |
console.error(arguments); | |
}, | |
}); | |
await audioEncoder.configure({ | |
codec: "opus", | |
bitrate: 64000, | |
numberOfChannels: 1, | |
sampleRate: 48000, | |
}); | |
const processor = new MediaStreamTrackProcessor(audioTrack); | |
const audioReader = processor.readable.getReader(); | |
async function read() { | |
let time = new Date().getTime(); | |
try { | |
while (new Date().getTime() - time < 5000) { | |
const {done, value} = await audioReader.read(); | |
if (done) { | |
break; | |
} | |
audioEncoder.encode(value); | |
} | |
} finally { | |
audioTrack.stop(); | |
console.log("record stop"); | |
} | |
} | |
console.log("record start"); | |
buf = []; | |
read(); | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment