-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.html
More file actions
984 lines (842 loc) · 40.4 KB
/
Copy pathexample.html
File metadata and controls
984 lines (842 loc) · 40.4 KB
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NSF Player - 专业音频播放器</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Inter', sans-serif;
background: linear-gradient(135deg, #0f0f23 0%, #1a1a3a 50%, #0f0f23 100%);
color: #e2e8f0;
min-height: 100vh;
overflow-x: hidden;
}
.glass-effect {
background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
}
.gradient-border {
position: relative;
background: linear-gradient(145deg, rgba(99, 102, 241, 0.1), rgba(168, 85, 247, 0.1));
border: 1px solid transparent;
}
.gradient-border::before {
content: '';
position: absolute;
inset: 0;
padding: 1px;
background: linear-gradient(145deg, #6366f1, #a855f7);
border-radius: inherit;
mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
mask-composite: exclude;
}
.floating-element {
animation: float 6s ease-in-out infinite;
}
@keyframes float {
0%, 100% { transform: translateY(0px); }
50% { transform: translateY(-10px); }
}
.pulse-glow {
animation: pulse-glow 2s ease-in-out infinite alternate;
}
@keyframes pulse-glow {
from { box-shadow: 0 0 20px rgba(99, 102, 241, 0.3); }
to { box-shadow: 0 0 40px rgba(99, 102, 241, 0.6); }
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 12px;
font-weight: 500;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
cursor: pointer;
border: none;
outline: none;
}
.btn-primary {
background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
color: white;
padding: 12px 24px;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 10px 25px rgba(99, 102, 241, 0.4);
}
.btn-icon {
display: flex;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.1);
color: #e2e8f0;
padding: 10px;
border-radius: 50%;
width: 44px;
height: 44px;
}
.btn-icon:hover {
background: rgba(255, 255, 255, 0.2);
transform: scale(1.05);
}
.play-button {
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #10b981 0%, #059669 100%);
color: white;
width: 60px;
height: 60px;
border-radius: 50%;
font-size: 20px;
}
.play-button:hover {
transform: scale(1.1);
box-shadow: 0 0 30px rgba(16, 185, 129, 0.5);
}
.sidebar {
width: 280px;
background: rgba(15, 15, 35, 0.8);
backdrop-filter: blur(20px);
border-right: 1px solid rgba(255, 255, 255, 0.1);
}
.card {
background: rgba(255, 255, 255, 0.08);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 16px;
transition: all 0.3s ease;
}
.card:hover {
background: rgba(255, 255, 255, 0.12);
transform: translateY(-2px);
}
.input-field {
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 8px;
padding: 10px 14px;
color: #e2e8f0;
transition: all 0.3s ease;
}
.input-field:focus {
outline: none;
border-color: #6366f1;
box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}
.waveform-container {
background: linear-gradient(135deg, rgba(16, 185, 129, 0.1) 0%, rgba(59, 130, 246, 0.1) 100%);
border-radius: 12px;
padding: 16px;
}
.status-indicator {
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 8px;
}
.status-playing { background-color: #10b981; animation: pulse 1.5s infinite; }
.status-stopped { background-color: #6b7280; }
.status-error { background-color: #ef4444; }
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.file-drop-zone {
border: 2px dashed rgba(99, 102, 241, 0.3);
border-radius: 16px;
transition: all 0.3s ease;
background: linear-gradient(135deg, rgba(99, 102, 241, 0.05) 0%, rgba(168, 85, 247, 0.05) 100%);
}
.file-drop-zone:hover {
border-color: #6366f1;
background: linear-gradient(135deg, rgba(99, 102, 241, 0.1) 0%, rgba(168, 85, 247, 0.1) 100%);
}
</style>
</head>
<body class="overflow-hidden">
<!-- 主容器 -->
<div class="flex h-screen">
<!-- 侧边栏 -->
<aside class="sidebar flex flex-col">
<div class="p-6 border-b border-white/10">
<h1 class="text-xl font-bold bg-gradient-to-r from-indigo-400 to-purple-400 bg-clip-text text-transparent">
NSF Player
</h1>
<p class="text-sm text-gray-400 mt-1">专业音频播放器</p>
</div>
<!-- 文件上传区域 -->
<div class="p-6 flex-1">
<div class="file-drop-zone p-6 text-center cursor-pointer mb-6" onclick="document.getElementById('nsfFile').click()">
<input type="file" id="nsfFile" accept=".nsf,.nsfe" class="hidden" onchange="loadNSF()">
<div class="w-12 h-12 mx-auto mb-3 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center">
<svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path>
</svg>
</div>
<h3 class="font-medium text-gray-200 mb-1">选择文件</h3>
<p class="text-sm text-gray-400">支持 NSF, NSFE 格式</p>
</div>
<!-- 轨道选择 -->
<div id="trackSelector" class="hidden mb-6">
<label class="block text-sm font-medium text-gray-300 mb-2">轨道选择</label>
<select id="trackSelect" class="w-full input-field">
</select>
</div>
<!-- 音量控制 -->
<div id="volumeControl" class="hidden mb-6">
<div class="flex items-center justify-between mb-2">
<label class="text-sm font-medium text-gray-300">音量</label>
<span id="volumeValue" class="text-sm text-gray-400">70%</span>
</div>
<input type="range" id="volumeSlider" min="0" max="100" value="70" class="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer slider">
</div>
<!-- 状态指示器 -->
<div id="statusPanel" class="hidden p-4 rounded-lg bg-black/20">
<div class="flex items-center mb-2">
<div id="statusIndicator" class="status-indicator status-stopped"></div>
<span id="playStatus" class="text-sm font-medium">准备就绪</span>
</div>
<div class="text-xs text-gray-400 space-y-1">
<div>轨道: <span id="currentTrack" class="text-gray-300">-</span></div>
<div>时间: <span id="playTime" class="text-gray-300 font-mono">00:00</span></div>
</div>
</div>
</div>
</aside>
<!-- 主内容区域 -->
<main class="flex-1 overflow-hidden">
<!-- 顶部状态栏 -->
<header class="glass-effect px-6 py-4 border-b border-white/10">
<div id="status" class="flex items-center text-sm">
<div class="w-2 h-2 bg-blue-400 rounded-full mr-2 animate-pulse"></div>
<span>准备就绪,请选择NSF文件开始播放</span>
</div>
</header>
<!-- 内容区域 -->
<div class="p-6 h-full overflow-y-auto">
<div id="welcomeScreen" class="flex items-center justify-center h-full">
<div class="text-center">
<div class="w-24 h-24 mx-auto mb-6 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center floating-element">
<svg class="w-12 h-12 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3"></path>
</svg>
</div>
<h2 class="text-2xl font-bold text-gray-200 mb-2">开始音频之旅</h2>
<p class="text-gray-400">选择一个NSF文件来体验高质量的复古游戏音乐</p>
</div>
</div>
<!-- 主要功能区域 -->
<div id="mainContent" class="hidden space-y-6">
<!-- 文件信息卡片 -->
<div class="card p-6">
<h2 class="text-lg font-semibold mb-4 flex items-center">
<svg class="w-5 h-5 mr-2 text-indigo-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
文件信息
</h2>
<div id="nsfInfo" class="grid grid-cols-1 lg:grid-cols-3 gap-4"></div>
</div>
<div class="grid lg:grid-cols-2 gap-6">
<!-- 播放控制器 -->
<div class="card p-6">
<h2 class="text-lg font-semibold mb-6 flex items-center">
<svg class="w-5 h-5 mr-2 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h1.586a1 1 0 01.707.293l2.414 2.414a1 1 0 00.707.293H15M9 10v4a2 2 0 002 2h2a2 2 0 002-2v-4M9 10V9a2 2 0 012-2h2a2 2 0 012 2v1.01"></path>
</svg>
实时播放
</h2>
<!-- 播放控制按钮 -->
<div class="flex items-center justify-center space-x-4 mb-6">
<button onclick="prevTrack()" class="btn-icon">
<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
<path d="M6 6h2v12H6zm3.5 6l8.5 6V6z"/>
</svg>
</button>
<button id="playBtn" onclick="togglePlay()" class="play-button pulse-glow">
<svg id="playIcon" class="w-7 h-7" fill="currentColor" viewBox="0 0 24 24">
<path d="M8 5v14l11-7z"/>
</svg>
</button>
<button onclick="stopPlay()" class="btn-icon">
<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
<path d="M6 6h12v12H6z"/>
</svg>
</button>
<button onclick="nextTrack()" class="btn-icon">
<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
<path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"/>
</svg>
</button>
</div>
<!-- 波形显示 -->
<div class="waveform-container">
<canvas id="waveform" class="w-full h-20 rounded-lg"></canvas>
</div>
</div>
<!-- WAV转换器 -->
<div class="card p-6">
<h2 class="text-lg font-semibold mb-6 flex items-center">
<svg class="w-5 h-5 mr-2 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path>
</svg>
WAV 转换
</h2>
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-300 mb-2">转换轨道</label>
<select id="wavTrackSelect" class="w-full input-field"></select>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-300 mb-2">时长 (ms)</label>
<input type="number" id="wavLength" value="120000" class="w-full input-field">
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-2">淡出 (ms)</label>
<input type="number" id="wavFade" value="5000" class="w-full input-field">
</div>
</div>
<button onclick="convertToWav()" class="btn-primary w-full flex items-center justify-center">
<svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 24 24">
<path d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
</svg>
生成 WAV 文件
</button>
<div id="wavStatus" class="text-sm"></div>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
<script>
let nsfPlayer = null;
let nsfInfo = null;
let audioContext = null;
let scriptProcessor = null;
let gainNode = null;
let isPlaying = false;
let currentTrack = 1;
let playStartTime = 0;
let audioBuffer = [];
let bufferSize = 4096;
let sampleRate = 44100;
let channels = 2;
// 显示状态
function showStatus(message, type = 'info') {
const statusElement = document.getElementById('status');
const indicator = statusElement.querySelector('div');
// 更新指示器颜色
indicator.className = 'w-2 h-2 rounded-full mr-2';
if (type === 'success') {
indicator.className += ' bg-green-400 animate-pulse';
} else if (type === 'error') {
indicator.className += ' bg-red-400 animate-pulse';
} else {
indicator.className += ' bg-blue-400 animate-pulse';
}
// 更新文本
statusElement.querySelector('span').textContent = message;
}
// 更新状态指示器
function updateStatusIndicator(status) {
const indicator = document.getElementById('statusIndicator');
const statusText = document.getElementById('playStatus');
indicator.className = 'status-indicator';
switch(status) {
case 'playing':
indicator.className += ' status-playing';
statusText.textContent = '播放中';
break;
case 'stopped':
indicator.className += ' status-stopped';
statusText.textContent = '已停止';
break;
case 'error':
indicator.className += ' status-error';
statusText.textContent = '错误';
break;
default:
indicator.className += ' status-stopped';
statusText.textContent = '准备就绪';
}
}
// 初始化WebAssembly
async function initWasm() {
if (nsfPlayer) return true;
try {
const script = document.createElement('script');
script.src = './build/nsf2wav_wasm.js';
return new Promise((resolve, reject) => {
script.onload = async () => {
try {
nsfPlayer = await NSFPlayer();
await new Promise(resolve => setTimeout(resolve, 200));
if (!nsfPlayer.ccall || !nsfPlayer._malloc || !nsfPlayer.HEAPU8) {
throw new Error('WebAssembly模块未完全初始化');
}
console.log('WebAssembly模块加载成功');
resolve(true);
} catch (error) {
reject(error);
}
};
script.onerror = reject;
document.head.appendChild(script);
});
} catch (error) {
showStatus('初始化失败: ' + error.message, 'error');
return false;
}
}
// 初始化Web Audio API
async function initAudio() {
if (audioContext) return true; // 如果已存在,则不重新创建
try {
audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: sampleRate
});
// 创建音频处理节点
scriptProcessor = audioContext.createScriptProcessor(bufferSize, 0, channels);
// 创建增益节点用于音量控制
gainNode = audioContext.createGain();
gainNode.gain.value = 0.7;
// 连接音频节点
scriptProcessor.connect(gainNode);
gainNode.connect(audioContext.destination);
// 音频处理回调
scriptProcessor.onaudioprocess = function(audioProcessingEvent) {
if (!isPlaying) {
// 输出静音
for (let channel = 0; channel < channels; channel++) {
const outputBuffer = audioProcessingEvent.outputBuffer.getChannelData(channel);
for (let sample = 0; sample < bufferSize; sample++) {
outputBuffer[sample] = 0;
}
}
return;
}
// 生成音频数据
generateAudioData(audioProcessingEvent.outputBuffer);
};
// 音量控制
const volumeSlider = document.getElementById('volumeSlider');
const volumeValue = document.getElementById('volumeValue');
volumeSlider.addEventListener('input', (e) => {
const volume = e.target.value / 100;
gainNode.gain.value = volume;
volumeValue.textContent = e.target.value + '%';
});
console.log('Web Audio API初始化成功');
return true;
} catch (error) {
console.error('Web Audio API初始化失败:', error);
showStatus('音频系统初始化失败: ' + error.message, 'error');
return false;
}
}
// 生成音频数据
function generateAudioData(outputBuffer) {
if (!nsfPlayer || !isPlaying) return;
try {
// 分配内存用于音频数据
const frameCount = bufferSize;
const audioDataSize = frameCount * channels * 2; // 16位立体声
const audioPtr = nsfPlayer._malloc(audioDataSize);
// 调用WebAssembly函数生成音频
const result = nsfPlayer.ccall('nsf_render_audio', 'number',
['number', 'number', 'number'], [currentTrack, frameCount, audioPtr]);
if (result > 0) {
// 读取生成的音频数据
const int16Data = new Int16Array(nsfPlayer.HEAPU8.buffer, audioPtr, frameCount * channels);
// 转换为Float32并填充输出缓冲区
for (let channel = 0; channel < channels; channel++) {
const outputData = outputBuffer.getChannelData(channel);
for (let sample = 0; sample < frameCount; sample++) {
const sampleIndex = sample * channels + channel;
outputData[sample] = int16Data[sampleIndex] / 32768.0;
}
}
// 更新波形显示
updateWaveform(outputBuffer.getChannelData(0));
} else {
// 如果没有数据,输出静音
for (let channel = 0; channel < channels; channel++) {
const outputData = outputBuffer.getChannelData(channel);
outputData.fill(0);
}
}
nsfPlayer._free(audioPtr);
} catch (error) {
console.error('音频生成错误:', error);
// 输出静音
for (let channel = 0; channel < channels; channel++) {
const outputData = outputBuffer.getChannelData(channel);
outputData.fill(0);
}
}
}
// 更新波形显示
function updateWaveform(audioData) {
const canvas = document.getElementById('waveform');
const ctx = canvas.getContext('2d');
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制波形背景网格
ctx.strokeStyle = 'rgba(99, 102, 241, 0.1)';
ctx.lineWidth = 0.5;
ctx.beginPath();
// 水平网格线
for (let i = 0; i <= 4; i++) {
const y = (canvas.height / 4) * i;
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
}
// 垂直网格线
for (let i = 0; i <= 10; i++) {
const x = (canvas.width / 10) * i;
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
}
ctx.stroke();
// 绘制波形
const gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop(0, '#10b981');
gradient.addColorStop(0.5, '#3b82f6');
gradient.addColorStop(1, '#8b5cf6');
ctx.strokeStyle = gradient;
ctx.lineWidth = 2;
ctx.shadowColor = '#10b981';
ctx.shadowBlur = 4;
ctx.beginPath();
const sliceWidth = canvas.width / audioData.length;
let x = 0;
for (let i = 0; i < audioData.length; i++) {
const v = audioData[i] * 0.4; // 略微减小振幅
const y = (v + 1) * canvas.height / 2;
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
x += sliceWidth;
}
ctx.stroke();
ctx.shadowBlur = 0; // 重置阴影
}
// 加载NSF文件
async function loadNSF() {
const fileInput = document.getElementById('nsfFile');
const file = fileInput.files[0];
if (!file) {
showStatus('请选择一个NSF文件', 'error');
return;
}
showStatus('正在初始化...', 'info');
// 如果已有音频在播放,先停止并清理
if (audioContext) {
stopPlay();
await audioContext.close();
audioContext = null;
scriptProcessor = null;
console.log('旧的AudioContext已清理');
}
// 重置UI状态
document.getElementById('mainContent').classList.add('hidden');
document.getElementById('welcomeScreen').classList.remove('hidden');
updateStatusIndicator('stopped');
document.getElementById('playTime').textContent = '00:00';
if (!(await initWasm())) return;
showStatus('正在加载NSF文件...', 'info');
try {
// 读取文件
const arrayBuffer = await file.arrayBuffer();
const nsfData = new Uint8Array(arrayBuffer);
// 初始化播放器
const initResult = nsfPlayer.ccall('init_nsf_player', 'number', [], []);
if (!initResult) {
throw new Error('初始化NSF播放器失败');
}
// 加载数据
const dataPtr = nsfPlayer._malloc(nsfData.length);
nsfPlayer.HEAPU8.set(nsfData, dataPtr);
const loadResult = nsfPlayer.ccall('load_nsf_data', 'number',
['number', 'number'], [dataPtr, nsfData.length]);
nsfPlayer._free(dataPtr);
if (!loadResult) {
throw new Error('加载NSF数据失败');
}
// 获取信息
const infoPtr = nsfPlayer._malloc(1024);
const infoResult = nsfPlayer.ccall('get_nsf_info', 'number', ['number'], [infoPtr]);
if (infoResult) {
nsfInfo = {
title: nsfPlayer.UTF8ToString(infoPtr),
artist: nsfPlayer.UTF8ToString(infoPtr + 256),
copyright: nsfPlayer.UTF8ToString(infoPtr + 512),
totalSongs: nsfPlayer.getValue(infoPtr + 768, 'i32'),
defaultSong: nsfPlayer.getValue(infoPtr + 772, 'i32'),
lengthMs: nsfPlayer.getValue(infoPtr + 776, 'i32'),
fadeMs: nsfPlayer.getValue(infoPtr + 780, 'i32')
};
displayNSFInfo();
setupTrackSelector();
setupWavExporter();
// 初始化音频系统
if (await initAudio()) {
// 设置C++播放器参数
nsfPlayer.ccall('nsf_player_set_options', 'void', ['number', 'number'], [sampleRate, channels]);
document.getElementById('mainContent').classList.remove('hidden');
showStatus('NSF文件加载成功!可以开始实时播放或转换为WAV。', 'success');
}
} else {
throw new Error('获取NSF信息失败');
}
nsfPlayer._free(infoPtr);
} catch (error) {
showStatus('加载失败: ' + error.message, 'error');
console.error('Error:', error);
}
}
// 显示NSF信息
function displayNSFInfo() {
const infoDiv = document.getElementById('nsfInfo');
infoDiv.innerHTML = `
<div class="bg-gradient-to-br from-indigo-500/10 to-purple-500/10 p-4 rounded-lg border border-indigo-500/20">
<div class="text-xs text-indigo-300 mb-1">标题</div>
<div class="font-medium text-white">${nsfInfo.title || '未知'}</div>
</div>
<div class="bg-gradient-to-br from-green-500/10 to-blue-500/10 p-4 rounded-lg border border-green-500/20">
<div class="text-xs text-green-300 mb-1">艺术家</div>
<div class="font-medium text-white">${nsfInfo.artist || '未知'}</div>
</div>
<div class="bg-gradient-to-br from-purple-500/10 to-pink-500/10 p-4 rounded-lg border border-purple-500/20">
<div class="text-xs text-purple-300 mb-1">版权</div>
<div class="font-medium text-white text-sm">${nsfInfo.copyright || '未知'}</div>
</div>
<div class="bg-gradient-to-br from-yellow-500/10 to-orange-500/10 p-4 rounded-lg border border-yellow-500/20">
<div class="text-xs text-yellow-300 mb-1">轨道数</div>
<div class="font-medium text-white">${nsfInfo.totalSongs} 首</div>
</div>
<div class="bg-gradient-to-br from-cyan-500/10 to-blue-500/10 p-4 rounded-lg border border-cyan-500/20">
<div class="text-xs text-cyan-300 mb-1">默认轨道</div>
<div class="font-medium text-white">第 ${nsfInfo.defaultSong + 1} 首</div>
</div>
`;
// 显示主内容区域,隐藏欢迎界面
document.getElementById('mainContent').classList.remove('hidden');
document.getElementById('welcomeScreen').classList.add('hidden');
document.getElementById('trackSelector').classList.remove('hidden');
document.getElementById('volumeControl').classList.remove('hidden');
document.getElementById('statusPanel').classList.remove('hidden');
}
// 设置轨道选择器
function setupTrackSelector() {
const trackSelect = document.getElementById('trackSelect');
const wavTrackSelect = document.getElementById('wavTrackSelect');
trackSelect.innerHTML = '';
wavTrackSelect.innerHTML = '';
for (let i = 1; i <= nsfInfo.totalSongs; i++) {
const option = document.createElement('option');
option.value = i;
option.textContent = `轨道 ${i}`;
const wavOption = option.cloneNode(true);
if (i === nsfInfo.defaultSong + 1) {
option.selected = true;
wavOption.selected = true;
currentTrack = i;
}
trackSelect.appendChild(option);
wavTrackSelect.appendChild(wavOption);
}
trackSelect.addEventListener('change', (e) => {
const newTrack = parseInt(e.target.value);
if (newTrack !== currentTrack) {
currentTrack = newTrack;
// 重置播放器到新轨道
if (nsfPlayer) {
nsfPlayer.ccall('nsf_set_track', 'void', ['number'], [currentTrack - 1]);
nsfPlayer.ccall('nsf_reset', 'void', [], []);
}
updateCurrentTrackDisplay();
}
});
}
function setupWavExporter() {
const wavLengthInput = document.getElementById('wavLength');
const wavFadeInput = document.getElementById('wavFade');
if (nsfInfo.lengthMs > 0) {
wavLengthInput.value = nsfInfo.lengthMs;
}
if (nsfInfo.fadeMs > 0) {
wavFadeInput.value = nsfInfo.fadeMs;
}
}
async function convertToWav() {
if (!nsfPlayer || !nsfInfo) {
showStatus('请先加载一个NSF文件。', 'error');
return;
}
const wavStatus = document.getElementById('wavStatus');
wavStatus.innerHTML = '<span class="text-yellow-400">正在转换,请稍候...</span>';
try {
const track = parseInt(document.getElementById('wavTrackSelect').value);
const lengthMs = parseInt(document.getElementById('wavLength').value);
const fadeMs = parseInt(document.getElementById('wavFade').value);
const wavSampleRate = 44100;
const wavChannels = 2;
// 估算最大可能的WAV大小并分配内存
const maxDurationMs = lengthMs + fadeMs;
const maxDataSize = (maxDurationMs / 1000) * wavSampleRate * wavChannels * 2;
const headerSize = 44;
const bufferSize = headerSize + maxDataSize;
const wavPtr = nsfPlayer._malloc(bufferSize);
if (!wavPtr) {
throw new Error('无法为WAV文件分配内存。');
}
// 调用C++函数
const wavSize = nsfPlayer.ccall('nsf_to_wav', 'number',
['number', 'number', 'number', 'number', 'number', 'number', 'number'],
[track, lengthMs, fadeMs, wavSampleRate, wavChannels, wavPtr, bufferSize]
);
if (wavSize > 0) {
const wavData = new Uint8Array(nsfPlayer.HEAPU8.buffer, wavPtr, wavSize);
const blob = new Blob([wavData], { type: 'audio/wav' });
const url = URL.createObjectURL(blob);
const fileName = `track_${track}.wav`;
wavStatus.innerHTML = `
<span class="text-green-400">转换成功!</span>
<a href="${url}" download="${fileName}" class="btn ml-4">下载WAV文件</a>
`;
} else {
throw new Error('WAV转换失败,C++函数返回0。');
}
nsfPlayer._free(wavPtr);
} catch (error) {
wavStatus.innerHTML = `<span class="text-red-400">转换错误: ${error.message}</span>`;
console.error('WAV conversion error:', error);
}
}
// 切换播放状态
async function togglePlay() {
if (!audioContext || !nsfPlayer) return;
if (audioContext.state === 'suspended') {
await audioContext.resume();
}
if (isPlaying) {
stopPlay();
} else {
startPlay();
}
}
// 开始播放
function startPlay() {
if (!nsfPlayer) return;
isPlaying = true;
playStartTime = Date.now();
// 设置播放器
nsfPlayer.ccall('nsf_set_track', 'void', ['number'], [currentTrack - 1]);
nsfPlayer.ccall('nsf_reset', 'void', [], []);
// 更新播放按钮图标为暂停
const playIcon = document.getElementById('playIcon');
playIcon.innerHTML = `
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
`;
// 更新状态
updateStatusIndicator('playing');
updateCurrentTrackDisplay();
// 开始播放时间更新
startPlayTimer();
showStatus('开始实时播放...', 'success');
}
// 停止播放
function stopPlay() {
isPlaying = false;
// 更新播放按钮图标为播放
const playIcon = document.getElementById('playIcon');
playIcon.innerHTML = `
<path d="M8 5v14l11-7z"/>
`;
// 更新状态
updateStatusIndicator('stopped');
document.getElementById('playTime').textContent = '00:00';
stopPlayTimer();
showStatus('播放已停止', 'info');
}
// 上一首
function prevTrack() {
if (currentTrack > 1) {
currentTrack--;
document.getElementById('trackSelect').value = currentTrack;
if (nsfPlayer) {
nsfPlayer.ccall('nsf_set_track', 'void', ['number'], [currentTrack - 1]);
nsfPlayer.ccall('nsf_reset', 'void', [], []);
}
updateCurrentTrackDisplay();
}
}
// 下一首
function nextTrack() {
if (currentTrack < nsfInfo.totalSongs) {
currentTrack++;
document.getElementById('trackSelect').value = currentTrack;
if (nsfPlayer) {
nsfPlayer.ccall('nsf_set_track', 'void', ['number'], [currentTrack - 1]);
nsfPlayer.ccall('nsf_reset', 'void', [], []);
}
updateCurrentTrackDisplay();
}
}
// 更新当前轨道显示
function updateCurrentTrackDisplay() {
document.getElementById('currentTrack').textContent = `轨道 ${currentTrack}`;
}
// 播放时间计时器
let playTimer = null;
function startPlayTimer() {
playTimer = setInterval(() => {
if (isPlaying) {
const elapsed = Math.floor((Date.now() - playStartTime) / 1000);
const minutes = Math.floor(elapsed / 60);
const seconds = elapsed % 60;
document.getElementById('playTime').textContent =
`${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
}, 1000);
}
function stopPlayTimer() {
if (playTimer) {
clearInterval(playTimer);
playTimer = null;
}
}
// 页面加载时初始化
window.addEventListener('load', async () => {
showStatus('准备就绪,请选择NSF文件开始实时播放');
});
// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
if (audioContext) {
audioContext.close();
}
if (nsfPlayer) {
nsfPlayer.ccall('cleanup', 'void', [], []);
}
});
</script>
</body>
</html>