Play Fix rich html
Plugin play fix html rich,sesuain aja ya ke strucktur bot kalian,apa bila tidak mau ribet download base script itsuki nakano ya..
JSJavaScriptPublicPluginsTanpa lisensi1 file · 716 baris · 26.6 KBDiperbarui 22 Okt 202697 views
https://codeku.itsuki-nakano.my.id/repo/alwayslenzz/play-fix-rich-htmlcurl -s https://codeku.itsuki-nakano.my.id/raw/alwayslenzz/play-fix-rich-htmlFILES
play.js · javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
/**
* play fix html
* sesuain sendiri loh yaa
* Base script :https://github.com/Nakano-pdf/itsuki-base
* Perintah:
* .play2 <judul lagu> -> cari lagu (10 hasil)
* .play2 <nomor> -> pilih hasil terakhir: thumbnail, audio penuh, dan kartu lirik
*
* API (sesuai contoh curl vamxapi):
* GET {BASE}/search/spotify?q=<judul>&limit=10 header: x-api-key
* respons: result.tracks[] { id, title, artist, album, duration, duration_ms, thumbnail,
* preview_url, spotify_url, download_api_url }
* GET {ORIGIN}{download_api_url} header: x-api-key -> audio penuh
*
* Key API: `.addapi vamx | https://vamxapi.my.id/api/v1 | <apiKey> | header | x-api-key`
* atau config.APIkey.vamx. Key tidak ditulis di dalam plugin.
* preview_url hanya cuplikan 30 detik, jadi TIDAK dikirim sebagai lagu penuh.
*/
/**
* Play2 v5 — Final YouTube (Vamx API) + Web Audio Player
* Struktur 100% mirip spotify3 (Anti Error 400 & Anti Blank)
*/
const axios = require('axios')
const config = require('../../config')
const { getApi } = require('../../src/lib/fixkit/store')
const { sendRichCard, esc } = require('../../src/lib/richCard')
const assetManager = require('../../src/lib/assetManager')
const { spawn } = require('child_process')
const fs = require('fs/promises')
const os = require('os')
const path = require('path')
const FOOT = '\n\n> ~ *いつき〜なかの✨* 🌸'
const SESSION_MS = 5 * 60 * 1000
const CHUNK = 3000
const LYRIC_MAX_LINES = 150
const API_NAME = 'vamx'
const LRCLIB = 'https://lrclib.net/api'
const OPUS_MIME = 'audio/webm;codecs=opus'
const OPUS_CHAIN = ['24k', '16k', '12k']
const MAX_B64_BYTES = 800_000
const pluginConfig = {
name: "play2",
alias: ["playaudio2"],
category: "search",
description: "Putar musik dari YouTube (Vamx API + Web Audio)",
usage: ".play2 <query> | .putar-play2 <url>",
example: ".play2 komang",
cooldown: 15,
energi: 1,
isEnabled: true
}
const sessions = new Map()
// ── Util ───────────────────────────────────────────────────────────────────
const fmtTime = (sec) => {
const s = Math.max(0, Math.floor(sec))
return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`
}
function fmtNumber(v) {
if (v === null || v === undefined || v === '') return ''
const n = Number(String(v).replace(/[^\d.-]/g, ''))
return isNaN(n) ? '' : n.toLocaleString('id-ID')
}
function toDataUri(buf) {
if (!buf || buf.length < 4) return ''
if (buf[0] === 0x89 && buf[1] === 0x50) return `data:image/png;base64,${buf.toString('base64')}`
if (buf.slice(0, 4).toString('ascii') === 'RIFF' && buf.slice(8, 12).toString('ascii') === 'WEBP') {
return `data:image/webp;base64,${buf.toString('base64')}`
}
return `data:image/jpeg;base64,${buf.toString('base64')}`
}
// ── API Vamx (Persis seperti spotify3) ──────────────────────────────────────
function buildAuth(api) {
const headers = {}, params = {}
if (api.authType === 'query') params[api.authName || 'apikey'] = api.apiKey
else if (api.authType === 'header') headers[api.authName || 'x-api-key'] = api.apiKey
else headers['x-api-key'] = api.apiKey
return { headers, params }
}
async function searchYouTube(q) {
const api = getApi(API_NAME)
if (!api?.baseURL || !api?.apiKey) throw new Error('API vamx belum terdaftar.')
const auth = buildAuth(api)
try {
const { data } = await axios.get(`${api.baseURL.replace(/\/$/, '')}/search/youtube`, {
params: { q, limit: 10, type: 'video', order: 'relevance', ...auth.params },
headers: auth.headers,
timeout: 25000,
})
return data?.result?.items || []
} catch (e) {
throw new Error(`Pencarian gagal: ${e.message}`)
}
}
async function downloadYouTubeAudio(track) {
const api = getApi(API_NAME)
if (!api?.baseURL || !api?.apiKey) throw new Error('API vamx belum terdaftar')
const auth = buildAuth(api)
try {
// Paksa tembak ke endpoint /download/youtube pakai parameter url
const { data } = await axios.get(`${api.baseURL.replace(/\/$/, '')}/download/youtube`, {
params: { url: track.url, ...auth.params },
headers: auth.headers,
responseType: 'arraybuffer',
timeout: 60000,
maxContentLength: 50 * 1024 * 1024,
})
const checkText = Buffer.from(data.slice(0, 500)).toString('utf-8')
if (checkText.trim().startsWith('{')) {
const json = JSON.parse(Buffer.from(data).toString('utf-8'))
const directUrl = json?.result?.url || json?.data?.url || json?.url
if (directUrl && directUrl.startsWith('http')) {
const audioRes = await axios.get(directUrl, { responseType: 'arraybuffer', timeout: 60000 })
return Buffer.from(audioRes.data)
}
throw new Error(json.message || 'Format respon API tidak valid')
}
return Buffer.from(data)
} catch (e) {
throw new Error(`Gagal unduh audio: ${e.message}`)
}
}
async function fetchThumb(url) {
if (!url) return null
try {
const { data } = await axios.get(url, { responseType: 'arraybuffer', timeout: 8000, maxContentLength: 5 * 1024 * 1024 })
return Buffer.from(data)
} catch { return null }
}
// ── Kompres Opus + Cek Limit ─────────────────────────
function compressOpus(inputBuffer, { bitrate, trimSec = 0, label = 'audio' }) {
return new Promise(async (resolve, reject) => {
const tmpDir = os.tmpdir()
const safe = String(label).replace(/[^a-zA-Z0-9]/g, '') || 'audio'
const stamp = `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`
const inPath = path.join(tmpDir, `op_in_${safe}_${stamp}.tmp`)
const outPath = path.join(tmpDir, `op_out_${safe}_${stamp}.webm`)
const cleanup = async () => {
try { await fs.unlink(inPath) } catch {}
try { await fs.unlink(outPath) } catch {}
}
try { await fs.writeFile(inPath, inputBuffer) }
catch (e) { await cleanup(); return reject(new Error(`tulis input: ${e.message}`)) }
const args = [
'-y', '-i', inPath,
...(trimSec > 0 ? ['-t', String(trimSec)] : []),
'-vn', '-ac', '1', '-ar', '48000',
'-c:a', 'libopus', '-b:a', bitrate, '-vbr', 'on',
'-application', 'audio', '-frame_duration', '40', '-compression_level', '10',
outPath,
]
const ff = spawn('ffmpeg', args)
let stderr = ''
ff.stderr.on('data', (d) => { stderr += d.toString() })
ff.on('error', async (e) => { await cleanup(); reject(new Error(`ffmpeg error: ${e.message}`)) })
ff.on('close', async (code) => {
if (code !== 0) { await cleanup(); return reject(new Error(`ffmpeg exit ${code}: ${stderr.slice(-300)}`)) }
try {
const out = await fs.readFile(outPath)
await cleanup()
if (!out?.byteLength) throw new Error('output kosong')
resolve(out)
} catch (e) { await cleanup(); reject(e) }
})
})
}
async function compressWithFallback(inputBuffer, durationSec, label) {
let best = null
for (const bitrate of OPUS_CHAIN) {
const buf = await compressOpus(inputBuffer, { bitrate, label })
const b64 = Math.ceil(buf.length * 4 / 3)
best = { buf, bitrate, b64len: b64, trimSec: 0 }
if (b64 <= MAX_B64_BYTES) return best
}
const targetRaw = Math.floor(MAX_B64_BYTES * 3 / 4)
const ratio = Math.min(1, targetRaw / best.buf.length) * 0.9
const trimSec = Math.max(90, Math.floor(durationSec * ratio))
const buf = await compressOpus(inputBuffer, { bitrate: OPUS_CHAIN[0], trimSec, label })
const b64 = Math.ceil(buf.length * 4 / 3)
if (b64 <= MAX_B64_BYTES) return { buf, bitrate: OPUS_CHAIN[0], b64len: b64, trimSec }
return best
}
// ── Lirik (LRCLIB) ─────────────────────────────────────────────────────────
async function getLyrics(title, artist, durationSec) {
try {
const { data } = await axios.get(`${LRCLIB}/get`, {
params: { artist_name: artist, track_name: title, duration: durationSec || undefined },
timeout: 20000,
})
if (data?.syncedLyrics) return { synced: data.syncedLyrics, plain: data.plainLyrics }
if (data?.plainLyrics) return { plain: data.plainLyrics }
} catch {}
try {
const { data } = await axios.get(`${LRCLIB}/search`, { params: { q: `${title} ${artist}` }, timeout: 20000 })
const arr = Array.isArray(data) ? data : []
const hit = arr.find((x) => x.syncedLyrics) || arr[0]
if (hit?.syncedLyrics) return { synced: hit.syncedLyrics, plain: hit.plainLyrics }
if (hit?.plainLyrics) return { plain: hit.plainLyrics }
} catch {}
return null
}
function parseLrc(lrc) {
const lines = []
const re = /\[(\d{1,3}):(\d{2})(?:[.:](\d{1,3}))?\]\s*(.*)/g
let m
while ((m = re.exec(lrc))) {
const text = (m[4] || '').trim()
if (!text) continue
const frac = m[3] ? Number(m[3].padEnd(3, '0')) / 1000 : 0
lines.push({ time: Number(m[1]) * 60 + Number(m[2]) + frac, text })
}
return lines.sort((a, b) => a.time - b.time)
}
// ── Kartu Pemutar (Web Audio API) ──────────────────────────────────────────
function buildPlayerHtml(track, lyr, { thumb = '', audioDataUri = '', totalSec = 0, bitrate = '', isTrimmed = false } = {}) {
let lines = []
let mode = 'none'
if (lyr?.synced) {
lines = parseLrc(lyr.synced)
if (lines.length) mode = 'synced'
}
if (!lines.length && lyr?.plain) {
lines = String(lyr.plain).split('\n').map((x) => x.trim()).filter(Boolean).map((text) => ({ time: null, text }))
mode = 'plain'
}
const total = totalSec || Math.floor((track.durationMs || 0) / 1000) || 180
if (isTrimmed) lines = lines.filter((l) => l.time === null || l.time <= total)
if (mode === 'plain' && total > 0 && lines.length) {
lines = lines.map((l, i) => ({ time: Math.round((i * total / lines.length) * 10) / 10, text: l.text }))
mode = 'estimated'
}
lines = lines.slice(0, LYRIC_MAX_LINES)
const body = lines.length
? lines.map((l, i) => `<div class="ln" data-i="${i}">${esc(l.text)}</div>`).join('')
: '<div class="none">Lirik tidak ditemukan untuk lagu ini 😢</div>'
const label = isTrimmed ? `🎬 Trim ${fmtTime(total)}` : (bitrate ? `🎧 Opus ${bitrate}` : '')
const hint = audioDataUri
? `Tekan ▶ untuk memutar audio. Lirik mengikuti posisi lagu.`
: 'Audio tidak tersedia. Pemutar hanya sebagai penanda waktu lirik.'
const data = JSON.stringify(lines.map((l) => ({ t: l.time, x: l.text })))
.replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')
const thumbHtml = thumb ? `<img class="th" src="${thumb}" alt="">` : ''
const audioHtml = audioDataUri ? `<audio id="audio-src" preload="auto" src="${audioDataUri}"></audio>` : ''
const detailParts = [track.album || 'YouTube']
if (track.views) detailParts.push(`👁️ ${fmtNumber(track.views)}`)
if (track.published) detailParts.push(`📅 ${track.published}`)
return `
<style>
*{box-sizing:border-box;margin:0;padding:0}
html,body{background:transparent!important}
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif;color:#fff;padding:2px}
.card{max-width:380px;margin:0 auto;border-radius:20px;overflow:hidden;background:linear-gradient(170deg,#1d1030,#0a0812 70%);border:2px solid rgba(255,255,255,.08)}
.hd{display:flex;gap:12px;align-items:center;padding:14px 16px 6px}
.th{width:72px;height:72px;border-radius:12px;object-fit:cover;flex:none;box-shadow:0 4px 14px rgba(0,0,0,.5)}
.hi{min-width:0}
.tt{font-size:16px;font-weight:800;line-height:1.25;word-break:break-word}
.ar{font-size:12px;opacity:.8;margin-top:3px}
.ab{font-size:10.5px;opacity:.55;margin-top:2px;line-height:1.3}
.badge{display:inline-block;font-size:10px;padding:2px 7px;border-radius:6px;background:rgba(255,77,122,.15);color:#ff8ba6;margin-top:5px}
.now{padding:10px 16px 0;text-align:center;min-height:74px}
.cur{font-size:18px;font-weight:800;line-height:1.35;min-height:48px;display:flex;align-items:center;justify-content:center}
.nxt{font-size:12px;opacity:.45;min-height:16px;margin-top:2px}
.tm{display:flex;justify-content:space-between;font-size:11px;opacity:.7;padding:6px 16px 0;font-variant-numeric:tabular-nums}
.bar{display:block;width:calc(100% - 32px);margin:4px 16px 0;accent-color:#ff4d7a}
.ctl{display:flex;gap:6px;padding:8px 12px 10px}
.btn{flex:1;border:0;border-radius:12px;padding:9px 6px;font-size:12px;font-weight:700;color:#fff;background:rgba(255,255,255,.1);cursor:pointer}
.btn.p{background:#ff4d7a;flex:1.4}
.btn:active{transform:scale(.97)}
.btn:disabled{opacity:.6;cursor:not-allowed}
.ly{position:relative;height:200px;overflow-y:auto;padding:4px 16px 50px;scroll-behavior:smooth;mask-image:linear-gradient(transparent,#000 10%,#000 90%,transparent)}
.ln{font-size:14px;line-height:1.5;padding:5px 0;color:rgba(255,255,255,.35);cursor:pointer;transition:color .2s,font-size .2s}
.ln.on{color:#fff;font-size:16px;font-weight:800}
.ln.past{color:rgba(255,255,255,.55)}
.none{font-size:13px;opacity:.7;padding:20px 0;text-align:center}
.st{font-size:10.5px;opacity:.55;text-align:center;padding:0 12px 12px}
</style>
<div class="card">
${audioHtml}
<div class="hd">
${thumbHtml}
<div class="hi">
<div class="tt">${esc(track.title)}</div>
<div class="ar">${esc(track.artist)}</div>
<div class="ab">${detailParts.join(' · ')}</div>
${label ? `<div class="badge">${esc(label)}</div>` : ''}
</div>
</div>
<div class="now">
<div class="cur" id="cur">Tekan ▶ untuk mulai</div>
<div class="nxt" id="nxt"></div>
</div>
<div class="tm"><span id="ct">00:00</span><span>${fmtTime(total)}</span></div>
<input class="bar" id="bar" type="range" min="0" max="${total}" step="0.1" value="0">
<div class="ctl">
<button class="btn" id="rw" disabled>−5 dtk</button>
<button class="btn p" id="pp" disabled>▶ Play</button>
<button class="btn" id="ff" disabled>+5 dtk</button>
</div>
<div class="ly" id="ly">${body}</div>
<div class="st" id="status">${hint}</div>
</div>
<script>
(function(){
var L=${data}, MODE='${mode}', TOTAL=${total};
var ly=document.getElementById('ly');
var rows=ly.querySelectorAll('.ln');
var cur=document.getElementById('cur'), nxt=document.getElementById('nxt');
var bar=document.getElementById('bar'), ct=document.getElementById('ct');
var pp=document.getElementById('pp');
var btnRw=document.getElementById('rw'), btnFf=document.getElementById('ff');
var statusDiv=document.getElementById('status');
var elSrc=document.getElementById('audio-src');
var pos=0, playing=false, last=Date.now(), seeking=false, lastIdx=-2;
var audioCtx = null;
var audioBuffer = null;
var sourceNode = null;
var isDecoded = false;
var startCtxTime = 0;
var pauseOffset = 0;
var isLoading = false;
function ensureContext() {
if (audioCtx) return audioCtx;
var Ctor = window.AudioContext || window.webkitAudioContext;
if (!Ctor) { statusDiv.textContent = 'Web Audio tidak didukung'; return null; }
audioCtx = new Ctor();
return audioCtx;
}
function dataUriToArrayBuffer(dataUri) {
var commaIndex = dataUri.indexOf(',');
var base64 = commaIndex >= 0 ? dataUri.slice(commaIndex + 1) : dataUri;
var binary = atob(base64);
var len = binary.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) bytes[i] = binary.charCodeAt(i);
return bytes.buffer;
}
function decodeAudio() {
return new Promise(function(resolve, reject) {
try {
var arrayBuffer = dataUriToArrayBuffer(elSrc.src);
var promise = audioCtx.decodeAudioData(arrayBuffer,
function(buffer) {
audioBuffer = buffer;
isDecoded = true;
bar.max = buffer.duration;
resolve(buffer);
},
function(err) { reject(err || new Error('decode error')); }
);
if (promise && typeof promise.then === 'function') {
promise.then(function(buffer) {
if (!isDecoded) { audioBuffer = buffer; isDecoded = true; bar.max = buffer.duration; resolve(buffer); }
}, function(){});
}
} catch (err) { reject(err); }
});
}
function stopSource() {
if (sourceNode) {
try { sourceNode.onended = null; sourceNode.stop(); } catch(e){}
try { sourceNode.disconnect(); } catch(e){}
sourceNode = null;
}
}
function startPlayback(offset) {
stopSource();
sourceNode = audioCtx.createBufferSource();
sourceNode.buffer = audioBuffer;
sourceNode.connect(audioCtx.destination);
var safeOffset = Math.max(0, Math.min(offset, audioBuffer.duration - 0.1));
sourceNode.start(0, safeOffset);
startCtxTime = audioCtx.currentTime - safeOffset;
pauseOffset = safeOffset;
playing = true;
isLoading = false;
setBtn();
}
async function loadAndDecode() {
if (!elSrc || !elSrc.src) return;
isLoading = true;
statusDiv.textContent = 'Memuat audio...';
try {
var ctx = ensureContext();
if (ctx.state === 'suspended') await ctx.resume();
await decodeAudio();
pp.disabled = false;
btnRw.disabled = false;
btnFf.disabled = false;
statusDiv.textContent = 'Audio siap! Tekan Play.';
isLoading = false;
} catch (e) {
statusDiv.textContent = '❌ Gagal decode: ' + e.message;
isLoading = false;
}
}
if(elSrc) loadAndDecode();
function fmt(s){s=Math.max(0,Math.floor(s));var m=Math.floor(s/60),r=s%60;return (m<10?'0':'')+m+':'+(r<10?'0':'')+r}
function idxAt(t){var i=-1;for(var k=0;k<L.length;k++){if(L[k].t===null)continue;if(L[k].t<=t)i=k;else break}return i}
function setBtn(){pp.textContent=playing?'⏸ Pause':'▶ Play'}
function render(){
if(!seeking){bar.value=pos;ct.textContent=fmt(pos)}
if(MODE==='synced'||MODE==='estimated'){
var i=idxAt(pos);
cur.textContent=i>=0?L[i].x:'· · ·';
nxt.textContent=i+1<L.length?L[i+1].x:'';
if(i!==lastIdx){
lastIdx=i;
for(var j=0;j<rows.length;j++){
rows[j].classList.toggle('on',j===i);
rows[j].classList.toggle('past',j<i)
}
if(i>=0&&rows[i]){
var el=rows[i];
ly.scrollTo({top:el.offsetTop-ly.clientHeight/2+el.clientHeight/2,behavior:'smooth'})
}
}
} else if(MODE==='plain'){cur.textContent='Lirik tanpa penanda waktu';nxt.textContent=''}
else {cur.textContent='🎶 '+fmt(pos);nxt.textContent=''}
}
function step(){
var n=Date.now();
if (isDecoded && playing && audioCtx) {
pos = audioCtx.currentTime - startCtxTime;
if (pos >= audioBuffer.duration) {
pos = audioBuffer.duration;
playing = false;
stopSource();
setBtn();
}
} else if (playing) {
pos += (n - last) / 1000;
if (pos >= TOTAL) { pos = TOTAL; playing = false; }
}
last = n; setBtn(); render();
}
function seekTo(t){
t = Math.max(0, Math.min(TOTAL, t));
if (isDecoded && playing) {
startPlayback(t);
} else {
pauseOffset = t; pos = t;
}
last = Date.now(); render();
}
pp.onclick = async function(){
if (isLoading) return;
if (!isDecoded) return;
var ctx = ensureContext();
if (!ctx) return;
if (ctx.state === 'suspended') await ctx.resume();
if (playing) {
pauseOffset = audioCtx.currentTime - startCtxTime;
stopSource();
playing = false;
setBtn();
} else {
if (pauseOffset >= audioBuffer.duration) pauseOffset = 0;
startPlayback(pauseOffset);
}
}
btnRw.onclick=function(){seekTo(pos-5)};
btnFf.onclick=function(){seekTo(pos+5)};
bar.oninput=function(){seeking=true;ct.textContent=fmt(parseFloat(this.value))};
bar.onchange=function(){seeking=false;seekTo(parseFloat(this.value))};
ly.onclick=function(e){
var el=e.target.closest?e.target.closest('.ln'):null;
if(!el)return;
var i=parseInt(el.getAttribute('data-i'),10);
if(L[i]&&L[i].t!==null)seekTo(L[i].t)
};
render();setInterval(step,250)
})()
</script>`
}
async function sendPlayerCard(m, sock, track, lyr, opts) {
const html = buildPlayerHtml(track, lyr, opts)
try {
return await sendRichCard(sock, m, {
title: '🎶 Pemutar Lirik',
footer: `${track.artist} · ${track.title}`,
html,
})
} catch (e) {
console.log('[PLAY2] kartu gagal, fallback teks:', e?.message || e)
}
if (!lyr) return m.reply(`📜 *ʟɪʀɪᴋ*\n\n_Lirik tidak ditemukan..._ 😢${FOOT}`)
const plain = lyr.synced ? parseLrc(lyr.synced).map(l => `[${fmtTime(l.time)}] ${l.text}`).join('\n') : lyr.plain
const chunks = plain.match(/[\s\S]{1,3000}/g) || []
for (const c of chunks) await m.reply(c + FOOT)
}
// ── Proses Putar (Persis spotify3) ─────────────────────────────────────────
async function processPlay(m, sock, url) {
try {
// Cari sesi
const sess = sessions.get(m.chat)
if (!sess || Date.now() - sess.createdAt > SESSION_MS) {
sessions.delete(m.chat)
m.react?.('❌')
return m.reply(`⌛ *ꜱᴇꜱɪ ʙᴇʀᴀᴋʜɪʀ* 🌸\n\nSesi pencarian sudah kedaluwarsa atau hilang. Cari ulang ya~${FOOT}`)
}
// Cari video dari data yang disimpen
const videoData = sess.results.find(v => v.url === url)
if (!videoData) {
m.react?.('❌')
return m.reply(`⚠️ Video tidak ditemukan di sesi. Cari ulang ya~${FOOT}`)
}
sess.createdAt = Date.now()
m.react?.('🎧')
await m.reply(`🎧 *ᴍᴇɴʏɪᴀᴘᴋᴀɴ ᴘᴇᴍᴜᴛᴀʀ...* 🪸\n\n_${videoData.title}_\n_⏳ Unduh & kompres audio, tunggu 15–40 detik..._${FOOT}`)
const durationSec = videoData.duration_seconds || 0
// Bersihin judul dari embel-embel (Official Video)
let artist = videoData.author.name || 'YouTube'
let title = videoData.title
if (title.includes(' - ')) {
const parts = title.split(' - ')
artist = parts[0].trim()
title = parts.slice(1).join(' - ').trim()
}
title = title.replace(/\(Official.*?\)|\[Official.*?\]|\(Lyric.*?\)/gi, '').trim()
// Paralel process
const [lyrR, thumbR, audioR] = await Promise.allSettled([
getLyrics(title, artist, durationSec),
fetchThumb(videoData.thumbnail),
downloadYouTubeAudio(videoData),
])
const lyrics = lyrR.status === 'fulfilled' ? lyrR.value : null
const thumb = thumbR.status === 'fulfilled' ? thumbR.value : null
const rawAudio = audioR.status === 'fulfilled' ? audioR.value : null
let audioDataUri = ''
let audioMeta = null
let audioErr = null
if (rawAudio && rawAudio.length > 0) {
try {
const c = await compressWithFallback(rawAudio, durationSec || 0, videoData.title)
audioDataUri = `data:${OPUS_MIME};base64,${c.buf.toString('base64')}`
audioMeta = c
console.log(`[PLAY2] kompres ok: ${c.bitrate} → ${Math.round(c.b64len / 1024)} KB`)
} catch (e) {
audioErr = e.message
console.error('[PLAY2] kompres gagal:', e)
}
} else if (audioR.status === 'rejected') {
audioErr = audioR.reason?.message || 'unduh gagal'
console.log('[PLAY2] Download API Error:', audioErr)
}
// KIRIM KARTU (Apapun yang terjadi, kartu tetap dikirim)
await sendPlayerCard(m, sock, {
title,
artist,
album: 'YouTube',
views: videoData.views,
published: videoData.published,
durationMs: durationSec * 1000
}, lyrics, {
thumb: toDataUri(thumb),
audioDataUri,
totalSec: audioMeta?.trimSec || durationSec,
isTrimmed: !!(audioMeta?.trimSec),
bitrate: audioMeta?.bitrate || '',
})
m.react?.('✅')
} catch (err) {
console.error('[PLAY2] Error fatal di processPlay:', err)
m.react?.('❌')
m.reply(`❌ Gagal memproses lagu: ${err.message}`)
}
}
// ── Main Handler ───────────────────────────────────────────────────────────
async function handler(m, { sock, text }) {
const query = m.text?.trim()
// Deteksi klik tombol PUTAR
if (query && query.startsWith('putar-play2 ')) {
const url = query.replace(/^putar-play2\s+/, '').trim()
return processPlay(m, sock, url)
}
if (!query) return m.reply(`🎵 *ᴘʟᴀʏ 2*\n\n> Contoh:\n\`${m.prefix}play2 komang\``)
m.react("🔍")
try {
const videos = await searchYouTube(query)
if (!videos.length) throw new Error("Video tidak ditemukan")
const video = videos[0]
// Simpan sesi pencarian
sessions.set(m.chat, { results: videos, createdAt: Date.now() })
const rows = videos.map((v, i) => {
return {
header: v.title.slice(0, 50),
title: v.author.name.slice(0, 24),
description: `⏱️ ${v.duration} · 👁️ ${fmtNumber(v.views)}`,
id: `${m.prefix}putar-play2 ${v.url}`
}
})
const botName = config.bot.name || 'Itsuki'
const caption = `🍀 *PLAY MUSIK*
Hai *${m.pushName}* 👋
╭┈┈⬡「 🎵 *ᴅᴇᴛᴀɪʟ ᴠɪᴅᴇᴏ* 」
┃ 🎤 *Channel:* ${video.author.name}
┃ ⏱️ *Durasi:* ${video.duration}
┃ 👁️ *Views:* ${fmtNumber(video.views)}
┃ 📅 *Rilis:* ${video.published}
┃ 🔗 *Link:* ${video.url}
╰┈┈┈┈┈┈┈┈⬡
Mau putar lagu ini? Tekan tombol "🍕 PUTAR" di bawah ya!
> ~ *${botName}* 🌸`
await sock.sendMessage(m.chat, {
image: { url: video.thumbnail },
caption: caption,
footer: botName,
interactiveButtons: [
{
name: 'quick_reply',
buttonParamsJson: JSON.stringify({
display_text: '🍕 PUTAR',
id: `${m.prefix}putar-play2 ${video.url}`
})
},
{
name: 'single_select',
buttonParamsJson: JSON.stringify({
title: 'Musik semacamnya',
sections: [{ title: 'List Musik yang hampir sama', rows }]
})
}
]
}, { quoted: m })
m.react("✅")
} catch (err) {
console.error('[Play2]', err)
m.react("❌")
m.reply(`❌ *Error*: ${err.message || err}`)
}
}
module.exports = {
config: pluginConfig,
handler
}PLAYGROUND
Siap
Klik Jalankan untuk melihat output.
Kode berjalan di kotak terisolasi di browser kamu. Tidak punya akses ke cookie, akun, atau server NAKANO CODE, dan tidak bisa membuka koneksi internet. Batas waktu 4 detik. Kode bot yang memanggil library WhatsApp (seperti Baileys) tidak bisa jalan di sini.