var player = document.getElementById('player');
player.onplay = function() {
var audioCtx = new AudioContext();
var source = audioCtx.createMediaElementSource(player);
var analyser = audioCtx.createAnalyser();
source.connect(analyser); // Подключаем анализатор к элементу audio
analyser.connect(audioCtx.destination); // Без этой строки нет звука, но анализатор работает.
var frequencyData = new Uint8Array(analyser.frequencyBinCount);
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
setInterval(function() {
analyser.getByteFrequencyData(frequencyData); // Записываем в массив данные уровней частот
ctx.fillStyle = "blue"; // Задаём цвет фона
ctx.globalAlpha = 0.05; // Это для получения эффекта плавного погасания полос
ctx.fillRect(0, 0, canvas.width, canvas.height); // Полупрозрачно чистим экран
ctx.fillStyle = "gold"; // Задаём цвет полос
ctx.globalAlpha = 1;
for (i = 0; i < 1024; i++) {
ctx.fillRect(i, 255 - frequencyData[i], 1, frequencyData[i]); // рисуем полосу
}
}, 20);
}
<audio id="player" controls src="https://listen6.myradio24.com/sazdan" crossorigin="anonymous"></audio>
<br/>
<br/>
<!--Подключаем файл-->
<canvas id="myCanvas" width=1024 height=256 style="background:blue"></canvas>
const arr = [1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 7, 8, 11, 13, 31, 31, 44, 51, 81, 65, 63];
const target = prompt("enter number", "52");
console.log('Список всех вариантов комбинаций:');
for(a = 0; a < 2 ** arr.length; a ++){
let sum = 0;
let result = '';
let b = a;
let r = 0;
while(r < arr.length){
let c = b;
b = Math.floor(b / 2);
if(b * 2 != c){
sum += arr[r];
result += ' + ' + arr[r];
}
r ++;
}
if(sum == target) console.log(result.substring(3));
}
<meta charset='utf-8' />
<script src="id3-minimized.js"></script>
<?php
$files = scandir('audio');
$id = 0;
for($i = 2; $i < count($files); $i ++){
echo '<table><tr><td>
<img id=picture'.$id.' />
</td><td>
<table class=list>
<tr><td><b>Название трека: </b></td><td></td></tr>
<tr><td><b>Исполнитель: </b></td><td></td></tr>
<tr><td><b>Альбом: </b></td><td></td></tr>
<tr><td><b>Жанр: </b></td><td></td></tr>
<tr><td><b>Год записи: </b></td><td></td></tr>
</table>
</tr></td></table>
<audio src="audio/'.$files[$i].'" controls></audio>';
$id ++;
}
?>
<script>
let id3Array = 'title, artist, album, genre, year, picture'.split(', ');
let tracs = document.querySelectorAll('audio');
let tags = [];
let amountOfTracks = <?=count($files) - 2; ?>;
for(j = 0; j < amountOfTracks; j ++){
let url = tracs[j].src;
ID3.loadTags(url, function() {
tags[j] = ID3.getAllTags(url);
let image = tags[j].picture;
if(image){
document.getElementById('picture' + j).style.display = 'block';
let base64String = "";
for(let i = 0; i < image.data.length; i ++) base64String += String.fromCharCode(image.data[i]);
let base64 = "data:" + image.format + ";base64," + window.btoa(base64String);
document.getElementById('picture' + j).src = base64;
}else{document.getElementById('picture' + j).style.display = 'none'};
},{
tags: id3Array
});
for(i = 0; i < id3Arraylength - 1; i ++) document.querySelectorAll('.list')[j].querySelectorAll('td')[i * 2 + 1].innerText = eval('tags[j].' + id3Array[i]);
}
</script>
<style>
li{
width: 200px;
border-radius: 5px;
}
</style>
<audio id=audio controls></audio><br /><br />
<b>Альбомы: </b>
<a href=# class=selectAlbum>album1</a> |
<a href=# class=selectAlbum>album2</a> |
<a href=# class=selectAlbum>album3</a><br /><br />
<b>Треки:</b>
<ul id=playlist></ul>
<script>
let selectedAlbum;
let album1=[
{
name: 'name1',
artist: 'artist1',
src: 'track1.mp3'
},
{
name: 'name2',
artist: 'artist2',
src: 'track2.mp3'
},
{
name: 'name3',
artist: 'artist3',
src: 'track3.mp3'
}
];
let album2=[
{
name: 'name4',
artist: 'artist4',
src: 'track4.mp3'
},
{
name: 'name5',
artist: 'artist5',
src: 'track5.mp3'
},
{
name: 'name6',
artist: 'artist6',
src: 'track6.mp3'
}
];
let album3=[
{
name: 'name7',
artist: 'artist7',
src: 'track7.mp3'
},
{
name: 'name8',
artist: 'artist8',
src: 'track8.mp3'
},
{
name: 'name9',
artist: 'artist9',
src: 'track9.mp3'
}
];
let albums = document.querySelectorAll('.selectAlbum');
for(i = 0; i < albums.length; i ++){
albums[i].onclick = function(){
audio.pause();
playlist.innerText = '';
selectedAlbum = eval(this.innerText);
for(j = 0; j < selectedAlbum.length; j ++){
let li = document.createElement('li');
li.id = j;
li.style.cursor = 'pointer';
li.innerHTML = ' ' + selectedAlbum[j].artist + ' - ' + selectedAlbum[j].name;
li.onclick = function(){
for(h = 0; h < selectedAlbum.length; h ++)document.getElementById(h).style.background = 'white';
this.style.background = 'gold';
audio.src = 'audio/' + selectedAlbum[this.id].src;
audio.play();
}
playlist.append(li);
}
}
}
</script>
<canvas id=canvas width=200 height=200></canvas>
let r = 90; // радиус
let amountOfPoints = 7; // количество точек
let x, y;
let ctx = canvas.getContext('2d');
for(i = 0; i < Math.PI * 2; i += Math.PI * 2 / amountOfPoints){
x = canvas.width / 2 + r * Math.sin(i);
y = canvas.height / 2 + r * Math.cos(i);
ctx.fillRect(x, y, 2, 2);
}
<html>
<head>
<title>визуализатор</title>
<meta charset="utf-8" />
<style>
body{
background: #003;
font-family: arial;
}
#myCanvas{
border-width: 3px;
border-color: white;
border-radius: 15px;
border-style: solid;
box-shadow: 0 0 15px 15px #7e7;
animation: spin-counter 5s linear infinite;
}
@keyframes spin-counter {
from{
box-shadow: 0 0 5px 5px #7e7;
border-color: white;
}
to{
box-shadow: 0 0 15px 15px pink;
border-color: gold;
}
}
</style>
</head>
<body><center>
<canvas id="myCanvas" width=1024 height=256 style="background:blue"></canvas><br /><br />
<audio src=sound.mp3' controls></audio>
</center></body>
<script>
var audio = document.querySelector('audio');
audio.onplay = function(){
var audioCtx = new AudioContext();
var source = audioCtx.createMediaElementSource(audio);
var analyser = audioCtx.createAnalyser();
source.connect(analyser); // Подключаем анализатор к элементу audio
analyser.connect(audioCtx.destination); // Без этой строки нет звука, но анализатор работает.
var frequencyData = new Uint8Array(analyser.frequencyBinCount);
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var counter = 0;
setInterval(function(){
analyser.getByteFrequencyData(frequencyData); // Записываем в массив данные уровней частот
ctx.fillStyle = "black"; // Задаём цвет фона
ctx.globalAlpha = 0.05; // Это для получения эффекта плавного погасания полос
ctx.fillRect (0, 0, canvas.width, canvas.height); // Полупрозрачно чистим экран
ctx.globalAlpha = 1;
ctx.strokeStyle = '#3f9';
ctx.beginPath();
ctx.moveTo(Math.floor(150 * Math.sin(counter / 1)), 255 - frequencyData[0]);
for(i = 1; i < 1024; i ++) ctx.lineTo(i + Math.floor(350 * Math.sin(i / 15)), 255 - frequencyData[i]);
ctx.stroke();
counter ++;
}, 20);
}
</script>
</html>
const a = 'https://www.w3schools.com/html/mov_bbb.mp4';
const b = 'https://assets.codepen.io/6093409/hubspot-video-example.mp4';
const arr = [a, b];
arr.map((item) => {
let media = new Audio(item);
media.onloadedmetadata = function () {
let date = new Date(this.duration * 1000);
let h = date.getUTCHours();
h = h ? h + ':' : '';
let m = date.getMinutes();
let s = date.getSeconds();
console.log(h + m + ':' + s);
};
});
<textarea id=txt oninput='send(this.value)'></textarea>
<script>
async function send(text){await fetch('script.php?text=' + text)};
async function get(){txt.value = await (await fetch('file.txt')).text()};
get();
setInterval(get, 5000);
txt.focus();
</script>
$text = $_GET['text'];
$file = fopen('file.txt', 'w');
fwrite($file, $text);
fclose($file);
<textarea id=txt cols=50 rows=10 oninput='array.push(this.value)' placeholder='введите текст:'></textarea><br /><br />
<button onclick='read()'> прочитать </button>
<button onclick='reset()'> очистить </button>
<script>
let array = [];
const read = _ => {
let index = 0;
let interval = setInterval(function(){
txt.value = array[index];
index ++;
if(index >= array.length) clearInterval(interval);
}, 300);
}
const reset = _ => {
txt.value = '';
array = [];
}
txt.focus();
</script>
Начальное значение:
<input id=r1 type=range value=20 oninput='n1.value = this.value' />
<input id=n1 type=number value=20 oninput='r1.value = this.value' /><br /><br />
Конечное значение:
<input id=r2 type=range value=80 oninput='n2.value = this.value' />
<input id=n2 type=number value=80 oninput='r2.value = this.value' />
<audio id=audio src="sound.mp3" controls></audio>
<img id=img src="image1.jpg" />
<button id=btn onclick="playPause()"> play </button>
const playPause = _ => {
if(audio.paused){
audio.play();
btn.textContent = " pause ";
img.src = "image2.jpg";
}else{
audio.pause();
btn.innerText = " play ";
img.src = "image1.jpg";
}
}
<style>
.btn__play{
width: 70px;
cursor: pointer;
border-radius: 10px;
}
</style>
track1: <button class=btn__play> Play </button><br /><br />
track2: <button class=btn__play> Play </button><br /><br />
track3: <button class=btn__play> Play </button>
<audio class=aud src='https://mysynthesizer.github.io/index.hetemeel/track1.mp3'></audio>
<audio class=aud src='https://mysynthesizer.github.io/index.hetemeel/track2.mp3'></audio>
<audio class=aud src='https://mysynthesizer.github.io/index.hetemeel/track3.mp3'></audio>
<script>
var btn = document.querySelectorAll('.btn__play');
var aud = document.querySelectorAll('.aud');
function playPause(index) {
btn[index].addEventListener('click', () => {
if(btn[index].textContent === 'Pause') {
btn[index].textContent = 'Play';
aud[index].pause();
} else {
btn[index].textContent = 'Pause';
aud[index].play();
}
});
}
for(i = 0; i < btn.length; i ++){
playPause(i);
aud[i].onended =_=> btn[i].textContent = 'Play';
}
</script>
<audio src='sound.mp3' controls loop></audio>
<style>
td{
width: 50px;
height: 25px;
text-align: center;
font-size: 20px;
}
hr{
width: 70%;
display: none;
}
</style>
<table cellspacing=0>
<tr id=numbers></tr>
<tr id=cursors></tr>
</table>
<script>
let index = 0;
let code = '';
let input = false;
for(i = 0; i < 4; i ++){
let number = document.createElement('td');
number.id = 'i' + i;
numbers.append(number);
let forcursor = document.createElement('td');
cursors.append(forcursor);
let cursor = document.createElement('hr');
cursor.id = 'c' + i;
forcursor.append(cursor);
}
const putSMSCode = _ => {
input = true;
document.getElementById('c' + index).style.display = 'block';
}
putSMSCode();
document.onkeydown = e => {
if(input){
if(index < 3){
document.getElementById('c' + (index + 1)).style.display = 'block';
}
document.getElementById('c' + index).style.display = 'none';
code += e.key;
document.getElementById('i' + index).innerHTML = '<b>' + e.key + '</b>';
index ++;
if (index >= 4) {
index = 0;
input = false;
console.log(code);
}
}
}
</script>
<html>
<head>
<meta charset="utf-8">
<title>Визуализатор</title>
<style>
#canvas{
position: absolute;
top: 50px;
left: 0px;
background: #333;
}
#progress{
position: absolute;
top: 50px;
left: 0px;
background: rgba(255, 155, 0, 0.5);
width: 0px;
height: 256px;
}
</style>
</head>
<body bgcolor=#444>
<audio id=audio src="sound.mp3" controls></audio>
<canvas id=canvas width=512 height=256></canvas>
<div id=progress></div>
<script>
var audio = document.getElementById("audio");
var ctx = canvas.getContext("2d");
var color_L = "#7cf", color_R = "#f7c"; // Цвета осциллограмм левого и правого стереоканалов
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
audio.onplay = function(){b = setInterval(function(){progress.style.width = Math.floor(audio.currentTime / audio.duration * canvas.width) + "px"}, 100)};
audio.onended = function(){
this.currentTime = 0;
clearInterval(b);
progress.style.width = "0px";
}
var source = audioCtx.createBufferSource();
var request = new XMLHttpRequest();
request.open('GET', audio.src, true);
request.responseType = 'arraybuffer';
request.onload = function(){
var audioData = request.response;
audioCtx.decodeAudioData(audioData, function(buffer){
source.buffer = buffer;
data_L = buffer.getChannelData(0);
data_R = buffer.getChannelData(1); // Если аудиофайл моно - поменяйте в этой сроке единицу на ноль.
// При несоответствии количества стереоканалов - ошибка в консоли и код не работает.
for(var i = 0; i < data_L.length; i++){
var x = Math.floor(i / data_L.length * canvas.width);
var L = data_L[i] * canvas.height / 4;
var R = data_R[i] * canvas.height / 4;
if(Math.floor(i / 16) == i / 16){ // Число 16 для больших аудиофайлов лучше побольше. Нужно подбирать.
ctx.fillStyle = color_L;
ctx.fillRect(x, canvas.height * 0.25 + L, 1, -L);
ctx.fillStyle = color_R;
ctx.fillRect(x, canvas.height * 0.75 + R, 1, -R);
}
}
},
function(e){"Error with decoding audio data" + e.err});
}
request.send();
canvas.onmousedown = progress.onmousedown = function(e){
progress.style.width = e.pageX + "px";
audio.currentTime = e.pageX / canvas.width * audio.duration;
}
canvas.ondblclick = function(){audio.play()};
ctx.fillStyle = color_L;
ctx.fillRect(0, canvas.height * 0.25, canvas.width, 1);
ctx.fillStyle = color_R;
ctx.fillRect(0, canvas.height * 0.75, canvas.width, 1);
</script>
</body>
</html>
<a href="http://site.com?id=1&name=vasya">Передать</a>
let result = new URL(location.href).searchParams.get("id"); // или get("name");
console.log(result);
<center>
<button id="startButton"> запись </button>
<button id="stopButton"> стоп </button><br /><br />
<video id="preview" width="320" height="240" style="border-style: solid" autoplay muted></video>
<video id="recording" width="320" height="240" controls hidden></video><br /><br />
<a id="downloadButton" hidden>скачать</a>
</center>
<script>
function startRecording(stream, lengthInMS) {
let recorder = new MediaRecorder(stream);
let data = [];
recorder.ondataavailable = event => data.push(event.data);
recorder.start();
let stopped = new Promise((resolve, reject) => {
recorder.onstop = resolve;
recorder.onerror = event => reject(event.name);
});
return Promise.all([stopped, new Promise(resolve => setTimeout(resolve, lengthInMS)).then(() => recorder.state == "съёмка" && recorder.stop())]).then(() => data);
}
startButton.addEventListener("click", function() {
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(stream => {
preview.srcObject = stream;
preview.captureStream = preview.captureStream;
return new Promise(resolve => preview.onplaying = resolve);
}).then(() => startRecording(preview.captureStream(), 5000)).then (recordedChunks => {
recording.hidden = false;
preview.hidden = true;
recording.src = downloadButton.href = URL.createObjectURL(new Blob(recordedChunks, { type: "video/webm" }));
recording.play();
downloadButton.hidden = false;
downloadButton.download = "RecordedVideo.webm";
});
}, false);
stopButton.addEventListener("click", function() {preview.srcObject.getTracks().forEach(track => track.stop())}, false);
recording.onended = () => recording.currentTime = 0;
</script>