@tiny-codes/react-easy 1.4.7 → 1.4.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/es/assets/request-camera-en.js +1 -1
- package/es/assets/request-camera-zh.js +1 -1
- package/es/assets/request-microphone-en.js +1 -1
- package/es/assets/request-microphone-zh.js +1 -1
- package/es/assets/reset-camera-en.js +1 -1
- package/es/assets/reset-camera-zh.js +1 -1
- package/es/assets/reset-microphone-en.js +1 -1
- package/es/assets/reset-microphone-zh.js +1 -1
- package/es/assets/save-default-audio1-en.js +1 -1
- package/es/assets/save-default-audio1-zh.js +1 -1
- package/es/assets/save-default-audio2-en.js +1 -1
- package/es/assets/save-default-audio2-zh.js +1 -1
- package/es/hooks/index.d.ts +6 -0
- package/es/hooks/index.js +6 -0
- package/es/hooks/index.js.map +1 -1
- package/es/hooks/useAudioPlayer.d.ts +7 -0
- package/es/hooks/useAudioPlayer.js +13 -0
- package/es/hooks/useAudioPlayer.js.map +1 -0
- package/es/hooks/useSSE.d.ts +26 -0
- package/es/hooks/useSSE.js +147 -0
- package/es/hooks/useSSE.js.map +1 -0
- package/es/hooks/useStompSocket.d.ts +63 -0
- package/es/hooks/useStompSocket.js +182 -0
- package/es/hooks/useStompSocket.js.map +1 -0
- package/es/hooks/useUserMedia.js +12 -24
- package/es/hooks/useUserMedia.js.map +1 -1
- package/es/locales/index.d.ts +6 -0
- package/es/locales/langs/en-US.d.ts +2 -0
- package/es/locales/langs/en-US.js +3 -1
- package/es/locales/langs/en-US.js.map +1 -1
- package/es/locales/langs/zh-CN.d.ts +2 -0
- package/es/locales/langs/zh-CN.js +3 -1
- package/es/locales/langs/zh-CN.js.map +1 -1
- package/es/utils/AudioPlayer.d.ts +159 -0
- package/es/utils/AudioPlayer.js +433 -0
- package/es/utils/AudioPlayer.js.map +1 -0
- package/es/utils/base64.d.ts +48 -0
- package/es/utils/base64.js +139 -0
- package/es/utils/base64.js.map +1 -0
- package/es/utils/crypto.d.ts +0 -30
- package/es/utils/crypto.js +8 -93
- package/es/utils/crypto.js.map +1 -1
- package/es/utils/index.d.ts +5 -1
- package/es/utils/index.js +5 -1
- package/es/utils/index.js.map +1 -1
- package/lib/hooks/index.d.ts +6 -0
- package/lib/hooks/index.js +17 -1
- package/lib/hooks/index.js.map +2 -2
- package/lib/hooks/useAudioPlayer.d.ts +7 -0
- package/lib/hooks/useAudioPlayer.js +42 -0
- package/lib/hooks/useAudioPlayer.js.map +7 -0
- package/lib/hooks/useSSE.d.ts +26 -0
- package/lib/hooks/useSSE.js +128 -0
- package/lib/hooks/useSSE.js.map +7 -0
- package/lib/hooks/useStompSocket.d.ts +63 -0
- package/lib/hooks/useStompSocket.js +154 -0
- package/lib/hooks/useStompSocket.js.map +7 -0
- package/lib/hooks/useUserMedia.js +12 -24
- package/lib/hooks/useUserMedia.js.map +2 -2
- package/lib/locales/index.d.ts +6 -0
- package/lib/locales/langs/en-US.d.ts +2 -0
- package/lib/locales/langs/en-US.js +3 -1
- package/lib/locales/langs/en-US.js.map +2 -2
- package/lib/locales/langs/zh-CN.d.ts +2 -0
- package/lib/locales/langs/zh-CN.js +3 -1
- package/lib/locales/langs/zh-CN.js.map +2 -2
- package/lib/utils/AudioPlayer.d.ts +159 -0
- package/lib/utils/AudioPlayer.js +284 -0
- package/lib/utils/AudioPlayer.js.map +7 -0
- package/lib/utils/base64.d.ts +48 -0
- package/lib/utils/base64.js +120 -0
- package/lib/utils/base64.js.map +7 -0
- package/lib/utils/crypto.d.ts +0 -30
- package/lib/utils/crypto.js +7 -66
- package/lib/utils/crypto.js.map +2 -2
- package/lib/utils/index.d.ts +5 -1
- package/lib/utils/index.js +28 -3
- package/lib/utils/index.js.map +2 -2
- package/package.json +10 -3
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
export type AudioSource = string | ReadableStreamDefaultReader<Uint8Array>;
|
|
2
|
+
export interface AudioPlayerInit {
|
|
3
|
+
/**
|
|
4
|
+
* - **EN:** Audio source (URL or streaming data)
|
|
5
|
+
* - **CN:** 音频源(URL或流数据)
|
|
6
|
+
*/
|
|
7
|
+
source?: AudioSource | (() => AudioSource | Promise<AudioSource>);
|
|
8
|
+
/**
|
|
9
|
+
* - **EN:** Initial volume level (0-1). Default is `0.5`
|
|
10
|
+
* - **CN:** 初始音量级别(0-1)。默认值为`0.5`
|
|
11
|
+
*/
|
|
12
|
+
volume?: number;
|
|
13
|
+
/**
|
|
14
|
+
* - **EN:** Callback when audio starts playing
|
|
15
|
+
* - **CN:** 音频开始播放时的回调
|
|
16
|
+
*/
|
|
17
|
+
onPlay?: () => void;
|
|
18
|
+
/**
|
|
19
|
+
* - **EN:** Callback when audio is paused
|
|
20
|
+
* - **CN:** 音频暂停时的回调
|
|
21
|
+
*/
|
|
22
|
+
onPause?: () => void;
|
|
23
|
+
/**
|
|
24
|
+
* - **EN:** Callback when audio is stopped
|
|
25
|
+
* - **CN:** 音频停止时的回调
|
|
26
|
+
*/
|
|
27
|
+
onStop?: () => void;
|
|
28
|
+
/**
|
|
29
|
+
* - **EN:** Callback when audio playback ends
|
|
30
|
+
* - **CN:** 音频播放结束时的回调
|
|
31
|
+
*/
|
|
32
|
+
onPlayEnd?: () => void;
|
|
33
|
+
/**
|
|
34
|
+
* - **EN:** Callback when an error occurs
|
|
35
|
+
* - **CN:** 发生错误时的回调
|
|
36
|
+
*/
|
|
37
|
+
onError?: (error: any) => void;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* - **EN:** An audio player class that supports URL or streaming data input
|
|
41
|
+
* - **CN:** 一个音频播放器类,支持URL或流数据输入
|
|
42
|
+
*/
|
|
43
|
+
declare class AudioPlayer {
|
|
44
|
+
private audio;
|
|
45
|
+
private volume;
|
|
46
|
+
private audioContext;
|
|
47
|
+
private gainNode;
|
|
48
|
+
private sourceNode;
|
|
49
|
+
private options;
|
|
50
|
+
private onPlayEnd;
|
|
51
|
+
/**
|
|
52
|
+
* - **EN:** Creates an audio player instance
|
|
53
|
+
* - **CN:** 创建音频播放器实例
|
|
54
|
+
*
|
|
55
|
+
* @param source - can be a URL string or ReadableStreamDefaultReader |
|
|
56
|
+
* 可以是URL字符串或ReadableStreamDefaultReader
|
|
57
|
+
*/
|
|
58
|
+
constructor(options?: AudioPlayerInit);
|
|
59
|
+
/**
|
|
60
|
+
* - **EN:** Check if audio is currently playing
|
|
61
|
+
* - **CN:** 检查音频是否正在播放
|
|
62
|
+
*/
|
|
63
|
+
get isPlaying(): boolean;
|
|
64
|
+
/**
|
|
65
|
+
* - **EN:** Play audio. If previously paused, will resume from the pause position
|
|
66
|
+
* - **CN:** 播放音频 如果之前暂停过,将从暂停位置继续播放
|
|
67
|
+
*/
|
|
68
|
+
play(): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* - **EN:** Set current playback time (in seconds)
|
|
71
|
+
* - **CN:** 设置当前播放时间(以秒为单位)
|
|
72
|
+
*
|
|
73
|
+
* @param time - time in seconds | 时间(秒)
|
|
74
|
+
*/
|
|
75
|
+
gotoTime(time: number): void;
|
|
76
|
+
/**
|
|
77
|
+
* - **EN:** Set playback position by percentage
|
|
78
|
+
* - **CN:** 按百分比设置播放位置
|
|
79
|
+
*
|
|
80
|
+
* @param percent - percentage (0-1) | 百分比(0-1)
|
|
81
|
+
*/
|
|
82
|
+
gotoPercent(percent: number): void;
|
|
83
|
+
/**
|
|
84
|
+
* - **EN:** Pause audio playback. When played again, will continue from current position
|
|
85
|
+
* - **CN:** 暂停音频播放 再次播放时将从当前位置继续
|
|
86
|
+
*/
|
|
87
|
+
pause(): void;
|
|
88
|
+
/**
|
|
89
|
+
* - **EN:** Stop audio playback. Progress will reset to the beginning
|
|
90
|
+
* - **CN:** 停止音频播放 进度会重置到开始位置
|
|
91
|
+
*/
|
|
92
|
+
stop(): void;
|
|
93
|
+
/**
|
|
94
|
+
* - **EN:** Update audio source
|
|
95
|
+
* - **CN:** 更新音频源
|
|
96
|
+
*
|
|
97
|
+
* @param source - can be a URL `string` or `ReadableStreamDefaultReader` |
|
|
98
|
+
* 可以是URL字符串或`ReadableStreamDefaultReader`
|
|
99
|
+
*/
|
|
100
|
+
setAudioSource(source?: AudioSource): Promise<void>;
|
|
101
|
+
/**
|
|
102
|
+
* - **EN:** Increase volume (by 10% each time)
|
|
103
|
+
* - **CN:** 增加音量(每次增加10%)
|
|
104
|
+
*
|
|
105
|
+
* @param percent - increase percentage (default 10%) | 增加百分比(默认10%)
|
|
106
|
+
*/
|
|
107
|
+
volumeUp(percent?: number): void;
|
|
108
|
+
/**
|
|
109
|
+
* - **EN:** Decrease volume (by 10% each time)
|
|
110
|
+
* - **CN:** 降低音量(每次降低10%)
|
|
111
|
+
*
|
|
112
|
+
* @param percent - decrease percentage (default 10%) | 降低百分比(默认10%)
|
|
113
|
+
*/
|
|
114
|
+
volumeDown(percent?: number): void;
|
|
115
|
+
/**
|
|
116
|
+
* - **EN:** Set volume to a specific value (0-1)
|
|
117
|
+
* - **CN:** 将音量设置为特定值(0-1)
|
|
118
|
+
*
|
|
119
|
+
* @param value - new volume value (0-1) | 新的音量值(0-1)
|
|
120
|
+
*/
|
|
121
|
+
setVolume(value: number): void;
|
|
122
|
+
/**
|
|
123
|
+
* - **EN:** Get current volume value (0-1)
|
|
124
|
+
* - **CN:** 获取当前音量值(0-1)
|
|
125
|
+
*/
|
|
126
|
+
getVolume(): number;
|
|
127
|
+
/**
|
|
128
|
+
* - **EN:** Get current playback time (seconds)
|
|
129
|
+
* - **CN:** 获取当前播放时间(秒)
|
|
130
|
+
*/
|
|
131
|
+
getCurrentTime(): number;
|
|
132
|
+
/**
|
|
133
|
+
* - **EN:** Get total audio duration (seconds)
|
|
134
|
+
* - **CN:** 获取音频总时长(秒)
|
|
135
|
+
*/
|
|
136
|
+
getDuration(): number;
|
|
137
|
+
/**
|
|
138
|
+
* - **EN:** Add audio event listener
|
|
139
|
+
* - **CN:** 添加音频事件监听器
|
|
140
|
+
*/
|
|
141
|
+
addEventListener: HTMLAudioElement['addEventListener'];
|
|
142
|
+
/**
|
|
143
|
+
* - **EN:** Remove audio event listener
|
|
144
|
+
* - **CN:** 移除音频事件监听器
|
|
145
|
+
*/
|
|
146
|
+
removeEventListener: HTMLAudioElement['removeEventListener'];
|
|
147
|
+
/**
|
|
148
|
+
* - **EN:** Release resources
|
|
149
|
+
* - **CN:** 释放资源
|
|
150
|
+
*/
|
|
151
|
+
dispose(): void;
|
|
152
|
+
/** Process streaming data source */
|
|
153
|
+
private handleStreamSource;
|
|
154
|
+
/** Initialize Web Audio API for better volume control */
|
|
155
|
+
private initAudioContext;
|
|
156
|
+
/** Update audio playback volume */
|
|
157
|
+
private updateVolume;
|
|
158
|
+
}
|
|
159
|
+
export default AudioPlayer;
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
|
|
19
|
+
// src/utils/AudioPlayer.ts
|
|
20
|
+
var AudioPlayer_exports = {};
|
|
21
|
+
__export(AudioPlayer_exports, {
|
|
22
|
+
default: () => AudioPlayer_default
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(AudioPlayer_exports);
|
|
25
|
+
var AudioPlayer = class {
|
|
26
|
+
/**
|
|
27
|
+
* - **EN:** Creates an audio player instance
|
|
28
|
+
* - **CN:** 创建音频播放器实例
|
|
29
|
+
*
|
|
30
|
+
* @param source - can be a URL string or ReadableStreamDefaultReader |
|
|
31
|
+
* 可以是URL字符串或ReadableStreamDefaultReader
|
|
32
|
+
*/
|
|
33
|
+
constructor(options) {
|
|
34
|
+
this.audioContext = null;
|
|
35
|
+
this.gainNode = null;
|
|
36
|
+
this.sourceNode = null;
|
|
37
|
+
/**
|
|
38
|
+
* - **EN:** Add audio event listener
|
|
39
|
+
* - **CN:** 添加音频事件监听器
|
|
40
|
+
*/
|
|
41
|
+
this.addEventListener = (event, listener) => {
|
|
42
|
+
this.audio.addEventListener(event, listener);
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* - **EN:** Remove audio event listener
|
|
46
|
+
* - **CN:** 移除音频事件监听器
|
|
47
|
+
*/
|
|
48
|
+
this.removeEventListener = (event, listener) => {
|
|
49
|
+
this.audio.removeEventListener(event, listener);
|
|
50
|
+
};
|
|
51
|
+
const { source, volume } = options || {};
|
|
52
|
+
this.options = options;
|
|
53
|
+
this.audio = new Audio();
|
|
54
|
+
this.volume = volume != null ? Math.min(1, Math.max(0, volume)) : 0.5;
|
|
55
|
+
this.audio.volume = this.volume;
|
|
56
|
+
if (typeof source === "function") {
|
|
57
|
+
const result = source();
|
|
58
|
+
if (typeof result === "object" && "then" in result && typeof result.then === "function") {
|
|
59
|
+
result.then((data) => this.setAudioSource(data));
|
|
60
|
+
} else {
|
|
61
|
+
this.setAudioSource(result);
|
|
62
|
+
}
|
|
63
|
+
} else {
|
|
64
|
+
this.setAudioSource(source);
|
|
65
|
+
}
|
|
66
|
+
this.onPlayEnd = () => {
|
|
67
|
+
var _a, _b;
|
|
68
|
+
(_b = (_a = this.options) == null ? void 0 : _a.onPlayEnd) == null ? void 0 : _b.call(_a);
|
|
69
|
+
};
|
|
70
|
+
this.addEventListener("ended", this.onPlayEnd);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* - **EN:** Check if audio is currently playing
|
|
74
|
+
* - **CN:** 检查音频是否正在播放
|
|
75
|
+
*/
|
|
76
|
+
get isPlaying() {
|
|
77
|
+
var _a;
|
|
78
|
+
return ((_a = this.audioContext) == null ? void 0 : _a.state) === "running";
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* - **EN:** Play audio. If previously paused, will resume from the pause position
|
|
82
|
+
* - **CN:** 播放音频 如果之前暂停过,将从暂停位置继续播放
|
|
83
|
+
*/
|
|
84
|
+
async play() {
|
|
85
|
+
var _a, _b, _c, _d, _e;
|
|
86
|
+
if (!this.audioContext) {
|
|
87
|
+
this.initAudioContext();
|
|
88
|
+
}
|
|
89
|
+
if (((_a = this.audioContext) == null ? void 0 : _a.state) === "suspended") {
|
|
90
|
+
await this.audioContext.resume();
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
await this.audio.play();
|
|
94
|
+
(_c = (_b = this.options) == null ? void 0 : _b.onPlay) == null ? void 0 : _c.call(_b);
|
|
95
|
+
} catch (error) {
|
|
96
|
+
console.error("Error playing audio:", error);
|
|
97
|
+
(_e = (_d = this.options) == null ? void 0 : _d.onError) == null ? void 0 : _e.call(_d, error);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* - **EN:** Set current playback time (in seconds)
|
|
102
|
+
* - **CN:** 设置当前播放时间(以秒为单位)
|
|
103
|
+
*
|
|
104
|
+
* @param time - time in seconds | 时间(秒)
|
|
105
|
+
*/
|
|
106
|
+
gotoTime(time) {
|
|
107
|
+
const newTime = Math.max(0, time);
|
|
108
|
+
if (!isNaN(this.audio.duration)) {
|
|
109
|
+
this.audio.currentTime = Math.min(newTime, this.audio.duration);
|
|
110
|
+
} else {
|
|
111
|
+
this.audio.currentTime = newTime;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* - **EN:** Set playback position by percentage
|
|
116
|
+
* - **CN:** 按百分比设置播放位置
|
|
117
|
+
*
|
|
118
|
+
* @param percent - percentage (0-1) | 百分比(0-1)
|
|
119
|
+
*/
|
|
120
|
+
gotoPercent(percent) {
|
|
121
|
+
if (isNaN(this.audio.duration)) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const clampedPercent = Math.min(1, Math.max(0, percent));
|
|
125
|
+
const newTime = this.audio.duration * clampedPercent;
|
|
126
|
+
this.audio.currentTime = newTime;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* - **EN:** Pause audio playback. When played again, will continue from current position
|
|
130
|
+
* - **CN:** 暂停音频播放 再次播放时将从当前位置继续
|
|
131
|
+
*/
|
|
132
|
+
pause() {
|
|
133
|
+
var _a, _b;
|
|
134
|
+
this.audio.pause();
|
|
135
|
+
(_b = (_a = this.options) == null ? void 0 : _a.onPause) == null ? void 0 : _b.call(_a);
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* - **EN:** Stop audio playback. Progress will reset to the beginning
|
|
139
|
+
* - **CN:** 停止音频播放 进度会重置到开始位置
|
|
140
|
+
*/
|
|
141
|
+
stop() {
|
|
142
|
+
var _a, _b;
|
|
143
|
+
this.audio.pause();
|
|
144
|
+
this.audio.currentTime = 0;
|
|
145
|
+
(_b = (_a = this.options) == null ? void 0 : _a.onStop) == null ? void 0 : _b.call(_a);
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* - **EN:** Update audio source
|
|
149
|
+
* - **CN:** 更新音频源
|
|
150
|
+
*
|
|
151
|
+
* @param source - can be a URL `string` or `ReadableStreamDefaultReader` |
|
|
152
|
+
* 可以是URL字符串或`ReadableStreamDefaultReader`
|
|
153
|
+
*/
|
|
154
|
+
async setAudioSource(source) {
|
|
155
|
+
this.audio.pause();
|
|
156
|
+
this.audio.src = "";
|
|
157
|
+
if (typeof source === "string") {
|
|
158
|
+
this.audio.src = source;
|
|
159
|
+
} else {
|
|
160
|
+
await this.handleStreamSource(source);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* - **EN:** Increase volume (by 10% each time)
|
|
165
|
+
* - **CN:** 增加音量(每次增加10%)
|
|
166
|
+
*
|
|
167
|
+
* @param percent - increase percentage (default 10%) | 增加百分比(默认10%)
|
|
168
|
+
*/
|
|
169
|
+
volumeUp(percent = 0.1) {
|
|
170
|
+
this.volume = Math.min(1, this.volume + percent);
|
|
171
|
+
this.updateVolume();
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* - **EN:** Decrease volume (by 10% each time)
|
|
175
|
+
* - **CN:** 降低音量(每次降低10%)
|
|
176
|
+
*
|
|
177
|
+
* @param percent - decrease percentage (default 10%) | 降低百分比(默认10%)
|
|
178
|
+
*/
|
|
179
|
+
volumeDown(percent = 0.1) {
|
|
180
|
+
this.volume = Math.max(0, this.volume - percent);
|
|
181
|
+
this.updateVolume();
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* - **EN:** Set volume to a specific value (0-1)
|
|
185
|
+
* - **CN:** 将音量设置为特定值(0-1)
|
|
186
|
+
*
|
|
187
|
+
* @param value - new volume value (0-1) | 新的音量值(0-1)
|
|
188
|
+
*/
|
|
189
|
+
setVolume(value) {
|
|
190
|
+
this.volume = Math.min(1, Math.max(0, value));
|
|
191
|
+
this.updateVolume();
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* - **EN:** Get current volume value (0-1)
|
|
195
|
+
* - **CN:** 获取当前音量值(0-1)
|
|
196
|
+
*/
|
|
197
|
+
getVolume() {
|
|
198
|
+
return this.volume;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* - **EN:** Get current playback time (seconds)
|
|
202
|
+
* - **CN:** 获取当前播放时间(秒)
|
|
203
|
+
*/
|
|
204
|
+
getCurrentTime() {
|
|
205
|
+
return this.audio.currentTime;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* - **EN:** Get total audio duration (seconds)
|
|
209
|
+
* - **CN:** 获取音频总时长(秒)
|
|
210
|
+
*/
|
|
211
|
+
getDuration() {
|
|
212
|
+
return this.audio.duration;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* - **EN:** Release resources
|
|
216
|
+
* - **CN:** 释放资源
|
|
217
|
+
*/
|
|
218
|
+
dispose() {
|
|
219
|
+
this.audio.pause();
|
|
220
|
+
this.audio.src = "";
|
|
221
|
+
this.removeEventListener("ended", this.onPlayEnd);
|
|
222
|
+
if (this.audioContext) {
|
|
223
|
+
try {
|
|
224
|
+
this.audioContext.close();
|
|
225
|
+
} catch (error) {
|
|
226
|
+
console.error("Error closing AudioContext:", error);
|
|
227
|
+
}
|
|
228
|
+
this.audioContext = null;
|
|
229
|
+
}
|
|
230
|
+
this.sourceNode = null;
|
|
231
|
+
this.gainNode = null;
|
|
232
|
+
}
|
|
233
|
+
/** Process streaming data source */
|
|
234
|
+
async handleStreamSource(reader) {
|
|
235
|
+
if (!reader)
|
|
236
|
+
return;
|
|
237
|
+
try {
|
|
238
|
+
const stream = new ReadableStream({
|
|
239
|
+
async pull(controller) {
|
|
240
|
+
try {
|
|
241
|
+
const { done, value } = await reader.read();
|
|
242
|
+
if (done) {
|
|
243
|
+
controller.close();
|
|
244
|
+
} else {
|
|
245
|
+
controller.enqueue(value);
|
|
246
|
+
}
|
|
247
|
+
} catch (err) {
|
|
248
|
+
controller.error(err);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
const response = new Response(stream);
|
|
253
|
+
const blob = await response.blob();
|
|
254
|
+
const url = URL.createObjectURL(blob);
|
|
255
|
+
this.audio.src = url;
|
|
256
|
+
this.audio.onload = () => {
|
|
257
|
+
URL.revokeObjectURL(url);
|
|
258
|
+
};
|
|
259
|
+
} catch (error) {
|
|
260
|
+
console.error("Error processing audio stream:", error);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/** Initialize Web Audio API for better volume control */
|
|
264
|
+
initAudioContext() {
|
|
265
|
+
if (this.audioContext)
|
|
266
|
+
return;
|
|
267
|
+
this.audioContext = new AudioContext();
|
|
268
|
+
this.sourceNode = this.audioContext.createMediaElementSource(this.audio);
|
|
269
|
+
this.gainNode = this.audioContext.createGain();
|
|
270
|
+
this.sourceNode.connect(this.gainNode);
|
|
271
|
+
this.gainNode.connect(this.audioContext.destination);
|
|
272
|
+
this.gainNode.gain.value = this.volume;
|
|
273
|
+
}
|
|
274
|
+
/** Update audio playback volume */
|
|
275
|
+
updateVolume() {
|
|
276
|
+
if (this.gainNode) {
|
|
277
|
+
this.gainNode.gain.value = this.volume;
|
|
278
|
+
} else {
|
|
279
|
+
this.audio.volume = this.volume;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
var AudioPlayer_default = AudioPlayer;
|
|
284
|
+
//# sourceMappingURL=AudioPlayer.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/utils/AudioPlayer.ts"],
|
|
4
|
+
"sourcesContent": ["export type AudioSource = string | ReadableStreamDefaultReader<Uint8Array>;\n\nexport interface AudioPlayerInit {\n /**\n * - **EN:** Audio source (URL or streaming data)\n * - **CN:** 音频源(URL或流数据)\n */\n source?: AudioSource | (() => AudioSource | Promise<AudioSource>);\n /**\n * - **EN:** Initial volume level (0-1). Default is `0.5`\n * - **CN:** 初始音量级别(0-1)。默认值为`0.5`\n */\n volume?: number;\n /**\n * - **EN:** Callback when audio starts playing\n * - **CN:** 音频开始播放时的回调\n */\n onPlay?: () => void;\n /**\n * - **EN:** Callback when audio is paused\n * - **CN:** 音频暂停时的回调\n */\n onPause?: () => void;\n /**\n * - **EN:** Callback when audio is stopped\n * - **CN:** 音频停止时的回调\n */\n onStop?: () => void;\n\n /**\n * - **EN:** Callback when audio playback ends\n * - **CN:** 音频播放结束时的回调\n */\n onPlayEnd?: () => void;\n /**\n * - **EN:** Callback when an error occurs\n * - **CN:** 发生错误时的回调\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onError?: (error: any) => void;\n}\n\n/**\n * - **EN:** An audio player class that supports URL or streaming data input\n * - **CN:** 一个音频播放器类,支持URL或流数据输入\n */\nclass AudioPlayer {\n private audio: HTMLAudioElement;\n private volume: number;\n private audioContext: AudioContext | null = null;\n private gainNode: GainNode | null = null;\n private sourceNode: MediaElementAudioSourceNode | null = null;\n private options: AudioPlayerInit | undefined;\n private onPlayEnd: () => void;\n\n /**\n * - **EN:** Creates an audio player instance\n * - **CN:** 创建音频播放器实例\n *\n * @param source - can be a URL string or ReadableStreamDefaultReader |\n * 可以是URL字符串或ReadableStreamDefaultReader\n */\n constructor(options?: AudioPlayerInit) {\n const { source, volume } = options || {};\n this.options = options;\n this.audio = new Audio();\n this.volume = volume != null ? Math.min(1.0, Math.max(0, volume)) : 0.5; // Default volume 50%\n this.audio.volume = this.volume;\n if (typeof source === 'function') {\n const result = source();\n if (typeof result === 'object' && 'then' in result && typeof result.then === 'function') {\n result.then((data) => this.setAudioSource(data));\n } else {\n this.setAudioSource(result as AudioSource);\n }\n } else {\n this.setAudioSource(source);\n }\n this.onPlayEnd = () => {\n this.options?.onPlayEnd?.();\n };\n this.addEventListener('ended', this.onPlayEnd);\n }\n\n /**\n * - **EN:** Check if audio is currently playing\n * - **CN:** 检查音频是否正在播放\n */\n public get isPlaying() {\n return this.audioContext?.state === 'running';\n }\n\n /**\n * - **EN:** Play audio. If previously paused, will resume from the pause position\n * - **CN:** 播放音频 如果之前暂停过,将从暂停位置继续播放\n */\n async play(): Promise<void> {\n if (!this.audioContext) {\n this.initAudioContext();\n }\n\n if (this.audioContext?.state === 'suspended') {\n await this.audioContext.resume();\n }\n\n try {\n await this.audio.play();\n this.options?.onPlay?.();\n } catch (error) {\n console.error('Error playing audio:', error);\n this.options?.onError?.(error);\n }\n }\n\n /**\n * - **EN:** Set current playback time (in seconds)\n * - **CN:** 设置当前播放时间(以秒为单位)\n *\n * @param time - time in seconds | 时间(秒)\n */\n gotoTime(time: number): void {\n // Ensure time is not less than 0\n const newTime = Math.max(0, time);\n\n // Ensure time is not greater than duration (if known)\n if (!isNaN(this.audio.duration)) {\n this.audio.currentTime = Math.min(newTime, this.audio.duration);\n } else {\n this.audio.currentTime = newTime;\n }\n }\n\n /**\n * - **EN:** Set playback position by percentage\n * - **CN:** 按百分比设置播放位置\n *\n * @param percent - percentage (0-1) | 百分比(0-1)\n */\n gotoPercent(percent: number): void {\n if (isNaN(this.audio.duration)) {\n return; // Can't set position if duration is unknown\n }\n\n // Clamp percent to 0-1 range\n const clampedPercent = Math.min(1, Math.max(0, percent));\n\n // Calculate time based on percentage\n const newTime = this.audio.duration * clampedPercent;\n this.audio.currentTime = newTime;\n }\n\n /**\n * - **EN:** Pause audio playback. When played again, will continue from current position\n * - **CN:** 暂停音频播放 再次播放时将从当前位置继续\n */\n pause(): void {\n this.audio.pause();\n this.options?.onPause?.();\n }\n\n /**\n * - **EN:** Stop audio playback. Progress will reset to the beginning\n * - **CN:** 停止音频播放 进度会重置到开始位置\n */\n stop(): void {\n this.audio.pause();\n this.audio.currentTime = 0;\n this.options?.onStop?.();\n }\n\n /**\n * - **EN:** Update audio source\n * - **CN:** 更新音频源\n *\n * @param source - can be a URL `string` or `ReadableStreamDefaultReader` |\n * 可以是URL字符串或`ReadableStreamDefaultReader`\n */\n async setAudioSource(source?: AudioSource) {\n this.audio.pause();\n this.audio.src = '';\n\n if (typeof source === 'string') {\n this.audio.src = source;\n } else {\n await this.handleStreamSource(source);\n }\n }\n\n /**\n * - **EN:** Increase volume (by 10% each time)\n * - **CN:** 增加音量(每次增加10%)\n *\n * @param percent - increase percentage (default 10%) | 增加百分比(默认10%)\n */\n volumeUp(percent = 0.1): void {\n this.volume = Math.min(1.0, this.volume + percent);\n this.updateVolume();\n }\n\n /**\n * - **EN:** Decrease volume (by 10% each time)\n * - **CN:** 降低音量(每次降低10%)\n *\n * @param percent - decrease percentage (default 10%) | 降低百分比(默认10%)\n */\n volumeDown(percent = 0.1): void {\n this.volume = Math.max(0, this.volume - percent);\n this.updateVolume();\n }\n\n /**\n * - **EN:** Set volume to a specific value (0-1)\n * - **CN:** 将音量设置为特定值(0-1)\n *\n * @param value - new volume value (0-1) | 新的音量值(0-1)\n */\n setVolume(value: number): void {\n this.volume = Math.min(1.0, Math.max(0, value));\n this.updateVolume();\n }\n\n /**\n * - **EN:** Get current volume value (0-1)\n * - **CN:** 获取当前音量值(0-1)\n */\n getVolume(): number {\n return this.volume;\n }\n\n /**\n * - **EN:** Get current playback time (seconds)\n * - **CN:** 获取当前播放时间(秒)\n */\n getCurrentTime(): number {\n return this.audio.currentTime;\n }\n\n /**\n * - **EN:** Get total audio duration (seconds)\n * - **CN:** 获取音频总时长(秒)\n */\n getDuration(): number {\n return this.audio.duration;\n }\n\n /**\n * - **EN:** Add audio event listener\n * - **CN:** 添加音频事件监听器\n */\n addEventListener: HTMLAudioElement['addEventListener'] = (\n event: string,\n listener: EventListenerOrEventListenerObject\n ): void => {\n this.audio.addEventListener(event, listener);\n };\n\n /**\n * - **EN:** Remove audio event listener\n * - **CN:** 移除音频事件监听器\n */\n removeEventListener: HTMLAudioElement['removeEventListener'] = (\n event: string,\n listener: EventListenerOrEventListenerObject\n ): void => {\n this.audio.removeEventListener(event, listener);\n };\n\n /**\n * - **EN:** Release resources\n * - **CN:** 释放资源\n */\n dispose(): void {\n this.audio.pause();\n this.audio.src = '';\n this.removeEventListener('ended', this.onPlayEnd);\n\n if (this.audioContext) {\n try {\n this.audioContext.close();\n } catch (error) {\n console.error('Error closing AudioContext:', error);\n }\n this.audioContext = null;\n }\n\n this.sourceNode = null;\n this.gainNode = null;\n }\n\n /** Process streaming data source */\n private async handleStreamSource(reader?: ReadableStreamDefaultReader<Uint8Array>) {\n if (!reader) return;\n try {\n // Create a new ReadableStream to read data from the reader\n const stream = new ReadableStream({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (err) {\n controller.error(err);\n }\n },\n });\n\n // Convert stream to Blob and create URL\n const response = new Response(stream);\n const blob = await response.blob();\n const url = URL.createObjectURL(blob);\n\n this.audio.src = url;\n\n // Release Blob URL after audio loads\n this.audio.onload = () => {\n URL.revokeObjectURL(url);\n };\n } catch (error) {\n console.error('Error processing audio stream:', error);\n }\n }\n\n /** Initialize Web Audio API for better volume control */\n private initAudioContext() {\n if (this.audioContext) return;\n\n this.audioContext = new AudioContext();\n this.sourceNode = this.audioContext.createMediaElementSource(this.audio);\n this.gainNode = this.audioContext.createGain();\n\n this.sourceNode.connect(this.gainNode);\n this.gainNode.connect(this.audioContext.destination);\n\n this.gainNode.gain.value = this.volume;\n }\n\n /** Update audio playback volume */\n private updateVolume(): void {\n if (this.gainNode) {\n this.gainNode.gain.value = this.volume;\n } else {\n this.audio.volume = this.volume;\n }\n }\n}\n\nexport default AudioPlayer;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA8CA,IAAM,cAAN,MAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBhB,YAAY,SAA2B;AAbvC,SAAQ,eAAoC;AAC5C,SAAQ,WAA4B;AACpC,SAAQ,aAAiD;AAsMzD;AAAA;AAAA;AAAA;AAAA,4BAAyD,CACvD,OACA,aACS;AACT,WAAK,MAAM,iBAAiB,OAAO,QAAQ;AAAA,IAC7C;AAMA;AAAA;AAAA;AAAA;AAAA,+BAA+D,CAC7D,OACA,aACS;AACT,WAAK,MAAM,oBAAoB,OAAO,QAAQ;AAAA,IAChD;AA1ME,UAAM,EAAE,QAAQ,OAAO,IAAI,WAAW,CAAC;AACvC,SAAK,UAAU;AACf,SAAK,QAAQ,IAAI,MAAM;AACvB,SAA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G;AAAA,MACzB;AAAA,IACF,SAAS,OAAP;AACA,cAAQ,MAAM,kCAAkC,KAAK;AAAA,IACvD;AAAA,EACF;AAAA;AAAA,EAGQ,mBAAmB;AACzB,QAAI,KAAK;AAAc;AAEvB,SAAK,eAAe,IAAI,aAAa;AACrC,SAAK,aAAa,KAAK,aAAa,yBAAyB,KAAK,KAAK;AACvE,SAAK,WAAW,KAAK,aAAa,WAAW;AAE7C,SAAK,WAAW,QAAQ,KAAK,QAAQ;AACrC,SAAK,SAAS,QAAQ,KAAK,aAAa,WAAW;AAEnD,SAAK,SAAS,KAAK,QAAQ,KAAK;AAAA,EAClC;AAAA;AAAA,EAGQ,eAAqB;AAC3B,QAAI,KAAK,UAAU;AACjB,WAAK,SAAS,KAAK,QAAQ,KAAK;AAAA,IAClC,OAAO;AACL,WAAK,MAAM,SAAS,KAAK;AAAA,IAC3B;AAAA,EACF;AACF;AAEA,IAAO,sBAAQ;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* - **EN:** Encode a UTF-8 string into Base64 (standard or URL-safe).
|
|
3
|
+
* - **CN:** 将 UTF-8 字符串编码为 Base64(标准或 URL 安全格式)。
|
|
4
|
+
*
|
|
5
|
+
* @param content Input text to encode | 要编码的输入文本
|
|
6
|
+
*
|
|
7
|
+
* @returns Base64 encoded string | Base64 编码后的字符串
|
|
8
|
+
*/
|
|
9
|
+
export declare function stringToBase64(content: string, opts?: {
|
|
10
|
+
/**
|
|
11
|
+
* - **EN:** Use URL-safe Base64 if true (replace +/ with -_ and strip =)
|
|
12
|
+
* - **CN:** 为 true 时使用 URL 安全 Base64(将 +/ 替换为 -_ 并去掉 =)
|
|
13
|
+
*/
|
|
14
|
+
urlSafe?: boolean;
|
|
15
|
+
}): string;
|
|
16
|
+
/**
|
|
17
|
+
* - EN: Decode a Base64 (standard or URL-safe) string into UTF-8 text.
|
|
18
|
+
* - CN: 将(标准或 URL 安全)Base64 字符串解码为 UTF-8 文本。
|
|
19
|
+
*
|
|
20
|
+
* @param content Base64 encoded string | Base64 编码字符串
|
|
21
|
+
*
|
|
22
|
+
* @returns Decoded UTF-8 string | 解码后的 UTF-8 字符串
|
|
23
|
+
*/
|
|
24
|
+
export declare function base64ToString(content: string, opts?: {
|
|
25
|
+
/**
|
|
26
|
+
* - **EN:** Use URL-safe Base64 if true (replace +/ with -_ and strip =)
|
|
27
|
+
* - **CN:** 为 true 时使用 URL 安全 Base64(将 +/ 替换为 -_ 并去掉 =)
|
|
28
|
+
*/
|
|
29
|
+
urlSafe?: boolean;
|
|
30
|
+
}): string;
|
|
31
|
+
/**
|
|
32
|
+
* - **EN:** Convert an ArrayBuffer to a Base64 encoded string.
|
|
33
|
+
* - **CN:** 将 ArrayBuffer 转换为 Base64 编码的字符串。
|
|
34
|
+
*
|
|
35
|
+
* @param buf The ArrayBuffer to convert | 要转换的 ArrayBuffer
|
|
36
|
+
*
|
|
37
|
+
* @returns The Base64 encoded string | Base64 编码的字符串
|
|
38
|
+
*/
|
|
39
|
+
export declare function arrayBufferToBase64(buf: ArrayBuffer): string;
|
|
40
|
+
/**
|
|
41
|
+
* - **EN:** Decode a Base64 (standard or URL-safe) string into an ArrayBuffer.
|
|
42
|
+
* - **CN:** 将(标准或 URL 安全)Base64 字符串解码为 ArrayBuffer。
|
|
43
|
+
*
|
|
44
|
+
* @param base64 The Base64 encoded string | Base64 编码的字符串
|
|
45
|
+
*
|
|
46
|
+
* @returns The decoded ArrayBuffer | 解码后的 ArrayBuffer
|
|
47
|
+
*/
|
|
48
|
+
export declare function base64ToArrayBuffer(base64: string): ArrayBuffer;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
|
|
19
|
+
// src/utils/base64.ts
|
|
20
|
+
var base64_exports = {};
|
|
21
|
+
__export(base64_exports, {
|
|
22
|
+
arrayBufferToBase64: () => arrayBufferToBase64,
|
|
23
|
+
base64ToArrayBuffer: () => base64ToArrayBuffer,
|
|
24
|
+
base64ToString: () => base64ToString,
|
|
25
|
+
stringToBase64: () => stringToBase64
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(base64_exports);
|
|
28
|
+
function stringToBase64(content, opts = {}) {
|
|
29
|
+
const { urlSafe = false } = opts;
|
|
30
|
+
if (content == null || content === "")
|
|
31
|
+
return "";
|
|
32
|
+
let base64;
|
|
33
|
+
const hasBuffer = typeof Buffer !== "undefined" && typeof Buffer.from === "function";
|
|
34
|
+
if (hasBuffer) {
|
|
35
|
+
base64 = Buffer.from(content, "utf8").toString("base64");
|
|
36
|
+
} else {
|
|
37
|
+
const encoder = new TextEncoder();
|
|
38
|
+
const bytes = encoder.encode(content);
|
|
39
|
+
let binary = "";
|
|
40
|
+
for (const i of bytes) {
|
|
41
|
+
binary += String.fromCharCode(i);
|
|
42
|
+
}
|
|
43
|
+
base64 = btoa(binary);
|
|
44
|
+
}
|
|
45
|
+
if (urlSafe) {
|
|
46
|
+
base64 = base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/u, "");
|
|
47
|
+
}
|
|
48
|
+
return base64;
|
|
49
|
+
}
|
|
50
|
+
function base64ToString(content, opts = {}) {
|
|
51
|
+
const { urlSafe = false } = opts;
|
|
52
|
+
if (content == null || content === "")
|
|
53
|
+
return "";
|
|
54
|
+
let normalized = content;
|
|
55
|
+
if (urlSafe) {
|
|
56
|
+
normalized = normalized.replace(/-/g, "+").replace(/_/g, "/");
|
|
57
|
+
}
|
|
58
|
+
const padNeeded = normalized.length % 4;
|
|
59
|
+
if (padNeeded === 2)
|
|
60
|
+
normalized += "==";
|
|
61
|
+
else if (padNeeded === 3)
|
|
62
|
+
normalized += "=";
|
|
63
|
+
else if (padNeeded === 1) {
|
|
64
|
+
throw new Error("Invalid Base64 string length");
|
|
65
|
+
}
|
|
66
|
+
const hasBuffer = typeof Buffer !== "undefined" && typeof Buffer.from === "function";
|
|
67
|
+
try {
|
|
68
|
+
if (hasBuffer) {
|
|
69
|
+
return Buffer.from(normalized, "base64").toString("utf8");
|
|
70
|
+
} else {
|
|
71
|
+
const binary = atob(normalized);
|
|
72
|
+
const len = binary.length;
|
|
73
|
+
const bytes = new Uint8Array(len);
|
|
74
|
+
for (let i = 0; i < len; i++) {
|
|
75
|
+
bytes[i] = binary.charCodeAt(i);
|
|
76
|
+
}
|
|
77
|
+
const decoder = new TextDecoder();
|
|
78
|
+
return decoder.decode(bytes);
|
|
79
|
+
}
|
|
80
|
+
} catch (e) {
|
|
81
|
+
throw new Error("Failed to decode Base64: " + (e instanceof Error ? e.message : String(e)));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function arrayBufferToBase64(buf) {
|
|
85
|
+
if (typeof Buffer !== "undefined") {
|
|
86
|
+
return Buffer.from(buf).toString("base64");
|
|
87
|
+
}
|
|
88
|
+
const bytes = new Uint8Array(buf);
|
|
89
|
+
const chunk = 32768;
|
|
90
|
+
let binary = "";
|
|
91
|
+
for (let i = 0; i < bytes.length; i += chunk) {
|
|
92
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
|
93
|
+
}
|
|
94
|
+
let base64 = btoa(binary);
|
|
95
|
+
const padding = (4 - base64.length % 4) % 4;
|
|
96
|
+
if (padding)
|
|
97
|
+
base64 += "=".repeat(padding);
|
|
98
|
+
return base64;
|
|
99
|
+
}
|
|
100
|
+
function base64ToArrayBuffer(base64) {
|
|
101
|
+
if (typeof Buffer !== "undefined") {
|
|
102
|
+
const buffer = Buffer.from(base64, "base64");
|
|
103
|
+
return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
|
|
104
|
+
}
|
|
105
|
+
const binaryString = atob(base64);
|
|
106
|
+
const len = binaryString.length;
|
|
107
|
+
const bytes = new Uint8Array(len);
|
|
108
|
+
for (let i = 0; i < len; i++) {
|
|
109
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
110
|
+
}
|
|
111
|
+
return bytes.buffer;
|
|
112
|
+
}
|
|
113
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
114
|
+
0 && (module.exports = {
|
|
115
|
+
arrayBufferToBase64,
|
|
116
|
+
base64ToArrayBuffer,
|
|
117
|
+
base64ToString,
|
|
118
|
+
stringToBase64
|
|
119
|
+
});
|
|
120
|
+
//# sourceMappingURL=base64.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/utils/base64.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * - **EN:** Encode a UTF-8 string into Base64 (standard or URL-safe).\n * - **CN:** 将 UTF-8 字符串编码为 Base64(标准或 URL 安全格式)。\n *\n * @param content Input text to encode | 要编码的输入文本\n *\n * @returns Base64 encoded string | Base64 编码后的字符串\n */\nexport function stringToBase64(\n content: string,\n opts: {\n /**\n * - **EN:** Use URL-safe Base64 if true (replace +/ with -_ and strip =)\n * - **CN:** 为 true 时使用 URL 安全 Base64(将 +/ 替换为 -_ 并去掉 =)\n */\n urlSafe?: boolean;\n } = {}\n): string {\n const { urlSafe = false } = opts;\n if (content == null || content === '') return '';\n\n let base64: string;\n const hasBuffer = typeof Buffer !== 'undefined' && typeof Buffer.from === 'function';\n if (hasBuffer) {\n // Node.js\n base64 = Buffer.from(content, 'utf8').toString('base64');\n } else {\n // Browser\n const encoder = new TextEncoder();\n const bytes = encoder.encode(content);\n let binary = '';\n for (const i of bytes) {\n binary += String.fromCharCode(i);\n }\n base64 = btoa(binary);\n }\n\n if (urlSafe) {\n // Replace chars and strip padding for URL-safe variant\n base64 = base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/u, '');\n }\n return base64;\n}\n\n/**\n * - EN: Decode a Base64 (standard or URL-safe) string into UTF-8 text.\n * - CN: 将(标准或 URL 安全)Base64 字符串解码为 UTF-8 文本。\n *\n * @param content Base64 encoded string | Base64 编码字符串\n *\n * @returns Decoded UTF-8 string | 解码后的 UTF-8 字符串\n */\nexport function base64ToString(\n content: string,\n opts: {\n /**\n * - **EN:** Use URL-safe Base64 if true (replace +/ with -_ and strip =)\n * - **CN:** 为 true 时使用 URL 安全 Base64(将 +/ 替换为 -_ 并去掉 =)\n */\n urlSafe?: boolean;\n } = {}\n): string {\n const { urlSafe = false } = opts;\n if (content == null || content === '') return '';\n\n let normalized = content;\n if (urlSafe) {\n normalized = normalized.replace(/-/g, '+').replace(/_/g, '/');\n }\n // Restore padding if stripped\n const padNeeded = normalized.length % 4;\n if (padNeeded === 2) normalized += '==';\n else if (padNeeded === 3) normalized += '=';\n else if (padNeeded === 1) {\n throw new Error('Invalid Base64 string length');\n }\n\n const hasBuffer = typeof Buffer !== 'undefined' && typeof Buffer.from === 'function';\n try {\n if (hasBuffer) {\n return Buffer.from(normalized, 'base64').toString('utf8');\n } else {\n const binary = atob(normalized);\n const len = binary.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n const decoder = new TextDecoder();\n return decoder.decode(bytes);\n }\n } catch (e) {\n throw new Error('Failed to decode Base64: ' + (e instanceof Error ? e.message : String(e)));\n }\n}\n\n/**\n * - **EN:** Convert an ArrayBuffer to a Base64 encoded string.\n * - **CN:** 将 ArrayBuffer 转换为 Base64 编码的字符串。\n *\n * @param buf The ArrayBuffer to convert | 要转换的 ArrayBuffer\n *\n * @returns The Base64 encoded string | Base64 编码的字符串\n */\nexport function arrayBufferToBase64(buf: ArrayBuffer): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(buf).toString('base64');\n }\n const bytes = new Uint8Array(buf);\n const chunk = 0x8000;\n let binary = '';\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunk));\n }\n let base64 = btoa(binary);\n // Add padding for Base64\n const padding = (4 - (base64.length % 4)) % 4;\n if (padding) base64 += '='.repeat(padding);\n return base64;\n}\n\n/**\n * - **EN:** Decode a Base64 (standard or URL-safe) string into an ArrayBuffer.\n * - **CN:** 将(标准或 URL 安全)Base64 字符串解码为 ArrayBuffer。\n *\n * @param base64 The Base64 encoded string | Base64 编码的字符串\n *\n * @returns The decoded ArrayBuffer | 解码后的 ArrayBuffer\n */\nexport function base64ToArrayBuffer(base64: string): ArrayBuffer {\n if (typeof Buffer !== 'undefined') {\n const buffer = Buffer.from(base64, 'base64');\n return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n }\n const binaryString = atob(base64);\n const len = binaryString.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes.buffer;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQO,SAAS,eACd,SACA,OAMI,CAAC,GACG;AACR,QAAM,EAAE,UAAU,MAAM,IAAI;AAC5B,MAAI,WAAW,QAAQ,YAAY;AAAI,WAAO;AAE9C,MAAI;AACJ,QAAM,Y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