gradio-pr-bot commited on
Commit
33bb662
·
verified ·
1 Parent(s): aca1e62

Upload folder using huggingface_hub

Browse files
6.4.0/audio/Example.svelte CHANGED
@@ -1,7 +1,13 @@
1
  <script lang="ts">
2
- export let value: string | null;
3
- export let type: "gallery" | "table";
4
- export let selected = false;
 
 
 
 
 
 
5
  </script>
6
 
7
  <div
 
1
  <script lang="ts">
2
+ let {
3
+ value,
4
+ type,
5
+ selected = false
6
+ }: {
7
+ value: string | null;
8
+ type: "gallery" | "table";
9
+ selected?: boolean;
10
+ } = $props();
11
  </script>
12
 
13
  <div
6.4.0/audio/Index.svelte CHANGED
@@ -1,11 +1,9 @@
1
  <svelte:options accessors={true} />
2
 
3
  <script lang="ts">
4
- import { tick } from "svelte";
5
  import { Gradio } from "@gradio/utils";
6
  import { StatusTracker } from "@gradio/statustracker";
7
- import type { LoadingStatus } from "@gradio/statustracker";
8
- import { onMount } from "svelte";
9
 
10
  import StaticAudio from "./static/StaticAudio.svelte";
11
  import InteractiveAudio from "./interactive/InteractiveAudio.svelte";
@@ -36,11 +34,10 @@
36
  (props as any).minimal ?? (gradio.props as any).minimal ?? false
37
  );
38
 
39
- // let uploading = $state(false);
40
  let active_source = $derived.by(() =>
41
  gradio.props.sources ? gradio.props.sources[0] : null
42
  );
43
- let initial_value = gradio.props.value;
44
 
45
  const handle_reset_value = (): void => {
46
  if (initial_value === null || gradio.props.value === initial_value) {
@@ -49,11 +46,15 @@
49
  gradio.props.value = initial_value;
50
  };
51
 
52
- let dragging: boolean;
 
 
 
 
53
 
54
  let color_accent = "darkorange";
55
 
56
- let waveform_settings = $derived({
57
  height: 50,
58
  barWidth: 2,
59
  barGap: 3,
@@ -63,7 +64,12 @@
63
  barRadius: 10,
64
  dragToSeek: true,
65
  normalize: true,
66
- minPxPerSec: 20
 
 
 
 
 
67
  });
68
 
69
  const trim_region_settings = {
@@ -79,13 +85,13 @@
79
  );
80
  }
81
 
82
- function handle_error({ detail }: CustomEvent<string>): void {
83
  const [level, status] = detail.includes("Invalid file type")
84
  ? ["warning", "complete"]
85
  : ["error", "error"];
86
  if (gradio.shared.loading_status) {
87
- gradio.shared.loading_status.status = status as LoadingStatus["status"];
88
- gradio.shared.loading_status.message = detail;
89
  }
90
  gradio.dispatch(level as "error" | "warning", detail);
91
  }
@@ -99,18 +105,7 @@
99
  });
100
 
101
  onMount(() => {
102
- color_accent = getComputedStyle(document?.documentElement).getPropertyValue(
103
- "--color-accent"
104
- );
105
  set_trim_region_colour();
106
- waveform_settings.waveColor =
107
- gradio.props.waveform_options.waveform_color || "#9ca3af";
108
- waveform_settings.progressColor =
109
- gradio.props.waveform_options.waveform_progress_color || color_accent;
110
- waveform_settings.mediaControls =
111
- gradio.props.waveform_options.show_controls;
112
- waveform_settings.sampleRate =
113
- gradio.props.waveform_options.sample_rate || 44100;
114
  });
115
  </script>
116
 
@@ -151,11 +146,11 @@
151
  gradio.dispatch("custom_button_click", { id });
152
  }}
153
  bind:playback_position={gradio.props.playback_position}
154
- on:share={(e) => gradio.dispatch("share", e.detail)}
155
- on:error={(e) => gradio.dispatch("error", e.detail)}
156
- on:play={() => gradio.dispatch("play")}
157
- on:pause={() => gradio.dispatch("pause")}
158
- on:stop={() => gradio.dispatch("stop")}
159
  />
160
  </Block>
161
  {:else}
@@ -191,44 +186,44 @@
191
  }}
192
  value={gradio.props.value}
193
  subtitles={gradio.props.subtitles}
194
- on:change={({ detail }) => (gradio.props.value = detail)}
195
- on:stream={({ detail }) => {
196
  gradio.props.value = detail;
197
  gradio.dispatch("stream", gradio.props.value);
198
  }}
199
- on:drag={({ detail }) => (dragging = detail)}
200
  root={gradio.shared.root}
201
  sources={gradio.props.sources}
202
- {active_source}
203
  pending={gradio.shared.loading_status.pending}
204
  streaming={gradio.props.streaming}
205
- bind:recording={gradio.props.recording}
206
  loop={gradio.props.loop}
207
  max_file_size={gradio.shared.max_file_size}
208
  {handle_reset_value}
209
  editable={gradio.props.editable}
210
  bind:dragging
211
  bind:playback_position={gradio.props.playback_position}
212
- on:edit={() => gradio.dispatch("edit")}
213
- on:play={() => gradio.dispatch("play")}
214
- on:pause={() => gradio.dispatch("pause")}
215
- on:stop={() => gradio.dispatch("stop")}
216
- on:start_recording={() => gradio.dispatch("start_recording")}
217
- on:pause_recording={() => gradio.dispatch("pause_recording")}
218
- on:stop_recording={(e) => {
219
  gradio.dispatch("stop_recording");
220
  gradio.dispatch("input");
221
  }}
222
- on:upload={() => {
223
  gradio.dispatch("upload");
224
  gradio.dispatch("input");
225
  }}
226
- on:clear={() => {
227
  gradio.dispatch("clear");
228
  gradio.dispatch("input");
229
  }}
230
- on:error={handle_error}
231
- on:close_stream={() => gradio.dispatch("close_stream", "stream")}
232
  i18n={gradio.i18n}
233
  {waveform_settings}
234
  waveform_options={gradio.props.waveform_options}
 
1
  <svelte:options accessors={true} />
2
 
3
  <script lang="ts">
4
+ import { onMount, tick } from "svelte";
5
  import { Gradio } from "@gradio/utils";
6
  import { StatusTracker } from "@gradio/statustracker";
 
 
7
 
8
  import StaticAudio from "./static/StaticAudio.svelte";
9
  import InteractiveAudio from "./interactive/InteractiveAudio.svelte";
 
34
  (props as any).minimal ?? (gradio.props as any).minimal ?? false
35
  );
36
 
 
37
  let active_source = $derived.by(() =>
38
  gradio.props.sources ? gradio.props.sources[0] : null
39
  );
40
+ let initial_value = $state(gradio.props.value);
41
 
42
  const handle_reset_value = (): void => {
43
  if (initial_value === null || gradio.props.value === initial_value) {
 
46
  gradio.props.value = initial_value;
47
  };
48
 
49
+ let dragging = $state(false);
50
+ let recording = $state(gradio.props.recording ?? false);
51
+ $effect(() => {
52
+ gradio.props.recording = recording;
53
+ });
54
 
55
  let color_accent = "darkorange";
56
 
57
+ let waveform_settings = $state({
58
  height: 50,
59
  barWidth: 2,
60
  barGap: 3,
 
64
  barRadius: 10,
65
  dragToSeek: true,
66
  normalize: true,
67
+ minPxPerSec: 20,
68
+ waveColor: gradio.props.waveform_options.waveform_color || "#9ca3af",
69
+ progressColor:
70
+ gradio.props.waveform_options.waveform_progress_color || color_accent,
71
+ mediaControls: gradio.props.waveform_options.show_controls ?? false,
72
+ sampleRate: gradio.props.waveform_options.sample_rate || 44100
73
  });
74
 
75
  const trim_region_settings = {
 
85
  );
86
  }
87
 
88
+ function handle_error(detail: string): void {
89
  const [level, status] = detail.includes("Invalid file type")
90
  ? ["warning", "complete"]
91
  : ["error", "error"];
92
  if (gradio.shared.loading_status) {
93
+ (gradio.shared.loading_status as any).status = status;
94
+ (gradio.shared.loading_status as any).message = detail;
95
  }
96
  gradio.dispatch(level as "error" | "warning", detail);
97
  }
 
105
  });
106
 
107
  onMount(() => {
 
 
 
108
  set_trim_region_colour();
 
 
 
 
 
 
 
 
109
  });
110
  </script>
111
 
 
146
  gradio.dispatch("custom_button_click", { id });
147
  }}
148
  bind:playback_position={gradio.props.playback_position}
149
+ onshare={(detail) => gradio.dispatch("share", detail)}
150
+ onerror={(e) => gradio.dispatch("error", e.detail)}
151
+ onplay={() => gradio.dispatch("play")}
152
+ onpause={() => gradio.dispatch("pause")}
153
+ onstop={() => gradio.dispatch("stop")}
154
  />
155
  </Block>
156
  {:else}
 
186
  }}
187
  value={gradio.props.value}
188
  subtitles={gradio.props.subtitles}
189
+ onchange={(detail) => (gradio.props.value = detail)}
190
+ onstream={(detail) => {
191
  gradio.props.value = detail;
192
  gradio.dispatch("stream", gradio.props.value);
193
  }}
194
+ ondrag={(detail) => (dragging = detail)}
195
  root={gradio.shared.root}
196
  sources={gradio.props.sources}
197
+ active_source={active_source || undefined}
198
  pending={gradio.shared.loading_status.pending}
199
  streaming={gradio.props.streaming}
200
+ bind:recording
201
  loop={gradio.props.loop}
202
  max_file_size={gradio.shared.max_file_size}
203
  {handle_reset_value}
204
  editable={gradio.props.editable}
205
  bind:dragging
206
  bind:playback_position={gradio.props.playback_position}
207
+ onedit={() => gradio.dispatch("edit")}
208
+ onplay={() => gradio.dispatch("play")}
209
+ onpause={() => gradio.dispatch("pause")}
210
+ onstop={() => gradio.dispatch("stop")}
211
+ onstart_recording={() => gradio.dispatch("start_recording")}
212
+ onpause_recording={() => gradio.dispatch("pause_recording")}
213
+ onstop_recording={() => {
214
  gradio.dispatch("stop_recording");
215
  gradio.dispatch("input");
216
  }}
217
+ onupload={() => {
218
  gradio.dispatch("upload");
219
  gradio.dispatch("input");
220
  }}
221
+ onclear={() => {
222
  gradio.dispatch("clear");
223
  gradio.dispatch("input");
224
  }}
225
+ onerror={handle_error}
226
+ onclose_stream={() => gradio.dispatch("close_stream", "stream")}
227
  i18n={gradio.i18n}
228
  {waveform_settings}
229
  waveform_options={gradio.props.waveform_options}
6.4.0/audio/interactive/InteractiveAudio.svelte CHANGED
@@ -1,5 +1,5 @@
1
  <script lang="ts">
2
- import { onDestroy, createEventDispatcher, tick } from "svelte";
3
  import { Upload, ModifyUpload } from "@gradio/upload";
4
  import { prepare_files, type FileData, type Client } from "@gradio/client";
5
  import { BlockLabel, ShareButton, CustomButton } from "@gradio/atoms";
@@ -16,51 +16,116 @@
16
  import type { IMediaRecorderConstructor } from "extendable-media-recorder";
17
  import { SelectSource } from "@gradio/atoms";
18
  import type { WaveformOptions, SubtitleData } from "../shared/types";
19
-
20
- export let value: null | FileData = null;
21
- export let subtitles: null | FileData | SubtitleData[] = null;
22
- export let label: string;
23
- export let root: string;
24
- export let loop: boolean;
25
- export let show_label = true;
26
  import type { CustomButton as CustomButtonType } from "@gradio/utils";
27
- export let buttons: (string | CustomButtonType)[] = ["download", "share"];
28
- export let on_custom_button_click: ((id: number) => void) | null = null;
29
- export let sources:
30
- | ["microphone"]
31
- | ["upload"]
32
- | ["microphone", "upload"]
33
- | ["upload", "microphone"] = ["microphone", "upload"];
34
- export let pending = false;
35
- export let streaming = false;
36
- export let i18n: I18nFormatter;
37
- export let waveform_settings: Record<string, any>;
38
- export let trim_region_settings = {};
39
- export let waveform_options: WaveformOptions = {};
40
- export let dragging: boolean;
41
- export let active_source: "microphone" | "upload";
42
- export let handle_reset_value: () => void = () => {};
43
- export let editable = true;
44
- export let max_file_size: number | null = null;
45
- export let upload: Client["upload"];
46
- export let stream_handler: Client["stream"];
47
- export let stream_every: number = 0.1;
48
- export let uploading = false;
49
- export let recording = false;
50
- export let class_name = "";
51
- export let upload_promise: Promise<any> | null = null;
52
- export let initial_value: FileData | null = null;
53
- export let playback_position = 0;
54
 
55
- export let time_limit: number | null = null;
56
- export let stream_state: "open" | "waiting" | "closed" = "closed";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- $: dispatch("drag", dragging);
 
 
59
 
60
  // TODO: make use of this
61
  // export let type: "normal" | "numpy" = "normal";
62
  let recorder: IMediaRecorder;
63
- let mode = "";
64
  let header: Uint8Array | undefined = undefined;
65
  let pending_stream: Uint8Array[] = [];
66
  let submit_pending_stream_on_pending_end = false;
@@ -76,24 +141,6 @@
76
  });
77
  }
78
 
79
- const dispatch = createEventDispatcher<{
80
- change: FileData | null;
81
- stream: FileData;
82
- edit: never;
83
- play: never;
84
- pause: never;
85
- stop: never;
86
- end: never;
87
- drag: boolean;
88
- error: string;
89
- upload: FileData;
90
- clear: undefined;
91
- start_recording: undefined;
92
- pause_recording: undefined;
93
- stop_recording: undefined;
94
- close_stream: undefined;
95
- }>();
96
-
97
  const to_blob_parts = (parts: Uint8Array[] | Blob[]): BlobPart[] =>
98
  parts.map((part) => {
99
  if (part instanceof Blob) return part;
@@ -117,7 +164,13 @@
117
  Boolean
118
  ) as FileData[]
119
  )[0];
120
- dispatch(event, value);
 
 
 
 
 
 
121
  };
122
 
123
  onDestroy(() => {
@@ -133,11 +186,11 @@
133
  stream = await navigator.mediaDevices.getUserMedia({ audio: true });
134
  } catch (err) {
135
  if (!navigator.mediaDevices) {
136
- dispatch("error", i18n("audio.no_device_support"));
137
  return;
138
  }
139
  if (err instanceof DOMException && err.name == "NotAllowedError") {
140
- dispatch("error", i18n("audio.allow_recording_access"));
141
  return;
142
  }
143
  throw err;
@@ -182,18 +235,20 @@
182
  }
183
  }
184
 
185
- $: if (submit_pending_stream_on_pending_end && pending === false) {
186
- submit_pending_stream_on_pending_end = false;
187
- if (header && pending_stream) {
188
- let blobParts: Uint8Array[] = [header].concat(pending_stream);
189
- pending_stream = [];
190
- dispatch_blob(blobParts, "stream");
 
 
191
  }
192
- }
193
 
194
  async function record(): Promise<void> {
195
  recording = true;
196
- dispatch("start_recording");
197
  if (!inited) await prepare_audio();
198
 
199
  header = undefined;
@@ -203,37 +258,42 @@
203
  }
204
 
205
  function clear(): void {
206
- dispatch("change", null);
207
- dispatch("clear");
208
  mode = "";
209
  value = null;
210
  }
211
 
212
- function handle_load({ detail }: { detail: FileData }): void {
213
  value = detail;
214
- dispatch("change", detail);
215
- dispatch("upload", detail);
216
  }
217
 
218
  async function stop(): Promise<void> {
219
  recording = false;
220
 
221
  if (streaming) {
222
- dispatch("close_stream");
223
- dispatch("stop_recording");
224
  recorder.stop();
225
 
226
  if (pending) {
227
  submit_pending_stream_on_pending_end = true;
228
  }
229
  dispatch_blob(audio_chunks, "stop_recording");
230
- dispatch("clear");
231
  mode = "";
232
  }
233
  }
234
 
235
- $: if (!recording && recorder) stop();
236
- $: if (recording && recorder) record();
 
 
 
 
 
237
  </script>
238
 
239
  <BlockLabel
@@ -247,9 +307,9 @@
247
  data-testid={label ? "waveform-" + label : "unlabelled-audio"}
248
  >
249
  <StreamingBar {time_limit} />
250
- {#if value === null || streaming}
251
  {#if active_source === "microphone"}
252
- <ModifyUpload {i18n} on:clear={clear} />
253
  {#if streaming}
254
  <StreamAudio
255
  {record}
@@ -270,9 +330,9 @@
270
  {waveform_settings}
271
  {waveform_options}
272
  {handle_reset_value}
273
- on:start_recording
274
- on:pause_recording
275
- on:stop_recording
276
  />
277
  {/if}
278
  {:else if active_source === "upload"}
@@ -280,24 +340,27 @@
280
  <Upload
281
  bind:upload_promise
282
  filetype="audio/aac,audio/midi,audio/mpeg,audio/ogg,audio/wav,audio/x-wav,audio/opus,audio/webm,audio/flac,audio/vnd.rn-realaudio,audio/x-ms-wma,audio/x-aiff,audio/amr,audio/*"
283
- on:load={handle_load}
284
  bind:dragging
285
  bind:uploading
286
- on:error={({ detail }) => dispatch("error", detail)}
287
  {root}
288
  {max_file_size}
289
  {upload}
290
  {stream_handler}
291
  aria_label={i18n("audio.drop_to_upload")}
292
  >
293
- <slot />
294
  </Upload>
295
  {/if}
296
  {:else}
297
  <ModifyUpload
298
  {i18n}
299
- on:clear={clear}
300
- on:edit={() => (mode = "edit")}
 
 
 
301
  download={buttons === null
302
  ? value.url
303
  : buttons.some((btn) => typeof btn === "string" && btn === "download")
@@ -310,11 +373,11 @@
310
  {#if btn === "share"}
311
  <ShareButton
312
  {i18n}
313
- on:error
314
- on:share
315
- formatter={async (value) => {
316
- if (!value) return "";
317
- let url = await uploadToHuggingFace(value.url, "url");
318
  return `<audio controls src="${url}"></audio>`;
319
  }}
320
  {value}
@@ -323,7 +386,7 @@
323
  {:else}
324
  <CustomButton
325
  button={btn}
326
- on_click={(id) => {
327
  if (on_custom_button_click) {
328
  on_custom_button_click(id);
329
  }
@@ -349,10 +412,10 @@
349
  {loop}
350
  bind:playback_position
351
  interactive
352
- on:stop
353
- on:play
354
- on:pause
355
- on:edit
356
  />
357
  {/if}
358
  <SelectSource {sources} bind:active_source handle_clear={clear} />
 
1
  <script lang="ts">
2
+ import { onDestroy } from "svelte";
3
  import { Upload, ModifyUpload } from "@gradio/upload";
4
  import { prepare_files, type FileData, type Client } from "@gradio/client";
5
  import { BlockLabel, ShareButton, CustomButton } from "@gradio/atoms";
 
16
  import type { IMediaRecorderConstructor } from "extendable-media-recorder";
17
  import { SelectSource } from "@gradio/atoms";
18
  import type { WaveformOptions, SubtitleData } from "../shared/types";
 
 
 
 
 
 
 
19
  import type { CustomButton as CustomButtonType } from "@gradio/utils";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ let {
22
+ value = $bindable(null),
23
+ subtitles = null,
24
+ label,
25
+ root,
26
+ loop,
27
+ show_label = true,
28
+ buttons = ["download", "share"],
29
+ on_custom_button_click = null,
30
+ sources = ["microphone", "upload"],
31
+ pending = false,
32
+ streaming = false,
33
+ i18n,
34
+ waveform_settings,
35
+ trim_region_settings = {},
36
+ waveform_options = {},
37
+ dragging = $bindable(false),
38
+ active_source = $bindable<"microphone" | "upload">("microphone"),
39
+ handle_reset_value = () => {},
40
+ editable = true,
41
+ max_file_size = null,
42
+ upload,
43
+ stream_handler,
44
+ stream_every = 0.1,
45
+ uploading = $bindable(false),
46
+ recording = $bindable(false),
47
+ class_name = "",
48
+ upload_promise = $bindable(),
49
+ initial_value = $bindable(),
50
+ playback_position = $bindable(),
51
+ time_limit = null,
52
+ stream_state = "closed",
53
+ onchange,
54
+ onstream,
55
+ onedit,
56
+ onplay,
57
+ onpause,
58
+ onstop,
59
+ ondrag,
60
+ onerror,
61
+ onupload,
62
+ onclear,
63
+ onstart_recording,
64
+ onpause_recording,
65
+ onstop_recording,
66
+ onclose_stream,
67
+ children
68
+ }: {
69
+ value?: null | FileData;
70
+ subtitles?: null | FileData | SubtitleData[];
71
+ label: string;
72
+ root: string;
73
+ loop?: boolean;
74
+ show_label?: boolean;
75
+ buttons?: (string | CustomButtonType)[];
76
+ on_custom_button_click?: ((id: number) => void) | null;
77
+ sources?:
78
+ | ["microphone"]
79
+ | ["upload"]
80
+ | ["microphone", "upload"]
81
+ | ["upload", "microphone"];
82
+ pending?: boolean;
83
+ streaming?: boolean;
84
+ i18n: I18nFormatter;
85
+ waveform_settings: Record<string, any>;
86
+ trim_region_settings?: Record<string, any>;
87
+ waveform_options?: WaveformOptions;
88
+ dragging?: boolean;
89
+ active_source?: "microphone" | "upload";
90
+ handle_reset_value?: () => void;
91
+ editable?: boolean;
92
+ max_file_size?: number | null;
93
+ upload: Client["upload"];
94
+ stream_handler: Client["stream"];
95
+ stream_every?: number;
96
+ uploading?: boolean;
97
+ recording?: boolean;
98
+ class_name?: string;
99
+ upload_promise?: Promise<any> | null;
100
+ initial_value?: FileData | null;
101
+ playback_position?: number;
102
+ time_limit?: number | null;
103
+ stream_state?: "open" | "waiting" | "closed";
104
+ onchange?: (value: FileData | null) => void;
105
+ onstream?: (value: FileData) => void;
106
+ onedit?: () => void;
107
+ onplay?: () => void;
108
+ onpause?: () => void;
109
+ onstop?: () => void;
110
+ ondrag?: (dragging: boolean) => void;
111
+ onerror?: (error: string) => void;
112
+ onupload?: (value: FileData) => void;
113
+ onclear?: () => void;
114
+ onstart_recording?: () => void;
115
+ onpause_recording?: () => void;
116
+ onstop_recording?: () => void;
117
+ onclose_stream?: () => void;
118
+ children?: import("svelte").Snippet;
119
+ } = $props();
120
 
121
+ $effect(() => {
122
+ ondrag?.(dragging);
123
+ });
124
 
125
  // TODO: make use of this
126
  // export let type: "normal" | "numpy" = "normal";
127
  let recorder: IMediaRecorder;
128
+ let mode = $state("");
129
  let header: Uint8Array | undefined = undefined;
130
  let pending_stream: Uint8Array[] = [];
131
  let submit_pending_stream_on_pending_end = false;
 
141
  });
142
  }
143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  const to_blob_parts = (parts: Uint8Array[] | Blob[]): BlobPart[] =>
145
  parts.map((part) => {
146
  if (part instanceof Blob) return part;
 
164
  Boolean
165
  ) as FileData[]
166
  )[0];
167
+ if (event === "stream") {
168
+ onstream?.(value);
169
+ } else if (event === "change") {
170
+ onchange?.(value);
171
+ } else if (event === "stop_recording") {
172
+ onstop_recording?.();
173
+ }
174
  };
175
 
176
  onDestroy(() => {
 
186
  stream = await navigator.mediaDevices.getUserMedia({ audio: true });
187
  } catch (err) {
188
  if (!navigator.mediaDevices) {
189
+ onerror?.(i18n("audio.no_device_support"));
190
  return;
191
  }
192
  if (err instanceof DOMException && err.name == "NotAllowedError") {
193
+ onerror?.(i18n("audio.allow_recording_access"));
194
  return;
195
  }
196
  throw err;
 
235
  }
236
  }
237
 
238
+ $effect(() => {
239
+ if (submit_pending_stream_on_pending_end && pending === false) {
240
+ submit_pending_stream_on_pending_end = false;
241
+ if (header && pending_stream) {
242
+ let blobParts: Uint8Array[] = [header].concat(pending_stream);
243
+ pending_stream = [];
244
+ dispatch_blob(blobParts, "stream");
245
+ }
246
  }
247
+ });
248
 
249
  async function record(): Promise<void> {
250
  recording = true;
251
+ onstart_recording?.();
252
  if (!inited) await prepare_audio();
253
 
254
  header = undefined;
 
258
  }
259
 
260
  function clear(): void {
261
+ onchange?.(null);
262
+ onclear?.();
263
  mode = "";
264
  value = null;
265
  }
266
 
267
+ function handle_load(detail: FileData): void {
268
  value = detail;
269
+ onchange?.(detail);
270
+ onupload?.(detail);
271
  }
272
 
273
  async function stop(): Promise<void> {
274
  recording = false;
275
 
276
  if (streaming) {
277
+ onclose_stream?.();
278
+ onstop_recording?.();
279
  recorder.stop();
280
 
281
  if (pending) {
282
  submit_pending_stream_on_pending_end = true;
283
  }
284
  dispatch_blob(audio_chunks, "stop_recording");
285
+ onclear?.();
286
  mode = "";
287
  }
288
  }
289
 
290
+ $effect(() => {
291
+ if (!recording && recorder) stop();
292
+ });
293
+
294
+ $effect(() => {
295
+ if (recording && recorder) record();
296
+ });
297
  </script>
298
 
299
  <BlockLabel
 
307
  data-testid={label ? "waveform-" + label : "unlabelled-audio"}
308
  >
309
  <StreamingBar {time_limit} />
310
+ {#if value == null || streaming}
311
  {#if active_source === "microphone"}
312
+ <ModifyUpload {i18n} onclear={clear} />
313
  {#if streaming}
314
  <StreamAudio
315
  {record}
 
330
  {waveform_settings}
331
  {waveform_options}
332
  {handle_reset_value}
333
+ onstartrecording={() => onstart_recording?.()}
334
+ onpauserecording={() => onpause_recording?.()}
335
+ onstoprecording={() => onstop_recording?.()}
336
  />
337
  {/if}
338
  {:else if active_source === "upload"}
 
340
  <Upload
341
  bind:upload_promise
342
  filetype="audio/aac,audio/midi,audio/mpeg,audio/ogg,audio/wav,audio/x-wav,audio/opus,audio/webm,audio/flac,audio/vnd.rn-realaudio,audio/x-ms-wma,audio/x-aiff,audio/amr,audio/*"
343
+ onload={handle_load}
344
  bind:dragging
345
  bind:uploading
346
+ onerror={(detail: string) => onerror?.(detail)}
347
  {root}
348
  {max_file_size}
349
  {upload}
350
  {stream_handler}
351
  aria_label={i18n("audio.drop_to_upload")}
352
  >
353
+ {#if children}{@render children()}{/if}
354
  </Upload>
355
  {/if}
356
  {:else}
357
  <ModifyUpload
358
  {i18n}
359
+ onclear={clear}
360
+ onedit={() => {
361
+ mode = "edit";
362
+ onedit?.();
363
+ }}
364
  download={buttons === null
365
  ? value.url
366
  : buttons.some((btn) => typeof btn === "string" && btn === "download")
 
373
  {#if btn === "share"}
374
  <ShareButton
375
  {i18n}
376
+ {onerror}
377
+ onshare={() => {}}
378
+ formatter={async (fileData: FileData) => {
379
+ if (!fileData || !fileData.url) return "";
380
+ let url = await uploadToHuggingFace(fileData.url, "url");
381
  return `<audio controls src="${url}"></audio>`;
382
  }}
383
  {value}
 
386
  {:else}
387
  <CustomButton
388
  button={btn}
389
+ on_click={(id: number) => {
390
  if (on_custom_button_click) {
391
  on_custom_button_click(id);
392
  }
 
412
  {loop}
413
  bind:playback_position
414
  interactive
415
+ {onstop}
416
+ {onplay}
417
+ {onpause}
418
+ {onedit}
419
  />
420
  {/if}
421
  <SelectSource {sources} bind:active_source handle_clear={clear} />
6.4.0/audio/package.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "name": "@gradio/audio",
3
- "version": "0.22.0",
4
  "description": "Gradio UI packages",
5
  "type": "module",
6
  "author": "",
 
1
  {
2
  "name": "@gradio/audio",
3
+ "version": "0.22.1",
4
  "description": "Gradio UI packages",
5
  "type": "module",
6
  "author": "",
6.4.0/audio/player/AudioPlayer.svelte CHANGED
@@ -1,5 +1,5 @@
1
  <script lang="ts">
2
- import { onMount } from "svelte";
3
  import { Music } from "@gradio/icons";
4
  import { format_time, type I18nFormatter } from "@gradio/utils";
5
  import WaveSurfer from "wavesurfer.js";
@@ -8,78 +8,98 @@
8
  import { Empty } from "@gradio/atoms";
9
  import type { FileData } from "@gradio/client";
10
  import type { WaveformOptions, SubtitleData } from "../shared/types";
11
- import { createEventDispatcher } from "svelte";
12
 
13
  import Hls from "hls.js";
14
 
15
- export let value: null | FileData = null;
16
- export let subtitles: null | string | SubtitleData[] = null;
17
- $: url = value?.url;
18
- export let label: string;
19
- export let i18n: I18nFormatter;
20
- export let dispatch_blob: (
21
- blobs: Uint8Array[] | Blob[],
22
- event: "stream" | "change" | "stop_recording"
23
- ) => Promise<void> = () => Promise.resolve();
24
- export let interactive = false;
25
- export let editable = true;
26
- export let trim_region_settings = {};
27
- export let waveform_settings: Record<string, any>;
28
- export let waveform_options: WaveformOptions;
29
- export let mode = "";
30
- export let loop: boolean;
31
- export let handle_reset_value: () => void = () => {};
32
- export let playback_position = 0;
33
- let old_playback_position = 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  let container: HTMLDivElement;
36
  let waveform: WaveSurfer | undefined;
37
- let waveform_ready = false;
38
  let waveform_component_wrapper: HTMLDivElement;
39
- let playing = false;
40
 
41
  let subtitle_container: HTMLDivElement;
42
 
43
  let timeRef: HTMLTimeElement;
44
  let durationRef: HTMLTimeElement;
45
- let audio_duration: number;
46
 
47
- let trimDuration = 0;
48
 
49
- let show_volume_slider = false;
50
  let audio_player: HTMLAudioElement;
51
 
52
  let stream_active = false;
53
- let subtitles_toggle = true;
54
  let subtitle_event_handlers: (() => void)[] = [];
55
 
56
- const dispatch = createEventDispatcher<{
57
- stop: undefined;
58
- play: undefined;
59
- pause: undefined;
60
- edit: undefined;
61
- end: undefined;
62
- load: undefined;
63
- }>();
64
-
65
- $: use_waveform =
66
- waveform_options.show_recording_waveform && !value?.is_stream;
67
-
68
- $: if (
69
- waveform_ready &&
70
- old_playback_position !== playback_position &&
71
- audio_duration
72
- ) {
73
- waveform?.seekTo(playback_position / audio_duration);
74
- old_playback_position = playback_position;
75
- }
76
 
77
  const create_waveform = (): void => {
78
  waveform = WaveSurfer.create({
79
  container: container,
80
  ...waveform_settings
81
  });
82
-
83
  if (subtitles && waveform) {
84
  if (subtitles_toggle) {
85
  add_subtitles_to_waveform(waveform, subtitles);
@@ -88,10 +108,9 @@
88
  }
89
  }
90
 
91
- if (value?.url && waveform) {
92
- waveform.load(value?.url);
93
- }
94
-
95
  waveform?.on("decode", (duration: any) => {
96
  audio_duration = duration;
97
  durationRef && (durationRef.textContent = format_time(duration));
@@ -104,17 +123,18 @@
104
  firstTimeUpdate = false;
105
  return;
106
  }
107
- old_playback_position = playback_position = currentTime;
 
108
  });
109
 
110
  waveform?.on("interaction", () => {
111
  const currentTime = waveform?.getCurrentTime() || 0;
112
  timeRef && (timeRef.textContent = format_time(currentTime));
113
- old_playback_position = playback_position = currentTime;
 
114
  });
115
 
116
  waveform?.on("ready", () => {
117
- waveform_ready = true;
118
  if (!waveform_settings.autoplay) {
119
  waveform?.stop();
120
  } else {
@@ -127,29 +147,36 @@
127
  waveform?.play();
128
  } else {
129
  playing = false;
130
- dispatch("stop");
131
  }
132
  });
133
  waveform?.on("pause", () => {
134
  playing = false;
135
- dispatch("pause");
136
  });
137
  waveform?.on("play", () => {
138
  playing = true;
139
- dispatch("play");
140
  });
141
 
142
  waveform?.on("load", () => {
143
- dispatch("load");
144
  });
145
  };
146
 
147
- $: if (use_waveform && container !== undefined && container !== null) {
148
- if (waveform !== undefined) waveform.destroy();
149
- container.innerHTML = "";
150
- create_waveform();
151
- playing = false;
152
- }
 
 
 
 
 
 
 
153
 
154
  const handle_trim_audio = async (
155
  start: number,
@@ -157,18 +184,16 @@
157
  ): Promise<void> => {
158
  mode = "";
159
  const decodedData = waveform?.getDecodedData();
160
- if (decodedData)
161
- await process_audio(
162
  decodedData,
163
  start,
164
  end,
165
  waveform_settings.sampleRate
166
- ).then(async (trimmedBlob: Uint8Array) => {
167
- await dispatch_blob([trimmedBlob], "change");
168
- waveform?.destroy();
169
- container.innerHTML = "";
170
- });
171
- dispatch("edit");
172
  };
173
 
174
  async function load_audio(data: string): Promise<void> {
@@ -181,13 +206,15 @@
181
  }
182
  }
183
 
184
- $: if (subtitles && waveform) {
185
- if (subtitles_toggle) {
186
- add_subtitles_to_waveform(waveform, subtitles);
187
- } else {
188
- hide_subtitles();
 
 
189
  }
190
- }
191
 
192
  function load_stream(value: FileData | null): void {
193
  if (!value || !value.is_stream || !value.url) return;
@@ -233,16 +260,21 @@
233
  }
234
  }
235
 
236
- $: if (audio_player && url) {
237
- load_audio(url);
238
- }
 
 
239
 
240
- $: if (audio_player && value?.is_stream) {
241
- load_stream(value);
242
- }
 
 
243
 
244
  onMount(() => {
245
- window.addEventListener("keydown", (e) => {
 
246
  if (!waveform || show_volume_slider) return;
247
 
248
  const is_focused_in_waveform =
@@ -254,7 +286,13 @@
254
  } else if (e.key === "ArrowLeft" && mode !== "edit") {
255
  skip_audio(waveform, -0.1);
256
  }
257
- });
 
 
 
 
 
 
258
  });
259
 
260
  async function add_subtitles_to_waveform(
@@ -354,10 +392,10 @@
354
  class:hidden={use_waveform}
355
  controls
356
  autoplay={waveform_settings.autoplay}
357
- on:load
358
  bind:this={audio_player}
359
- on:ended={() => dispatch("stop")}
360
- on:play={() => dispatch("play")}
361
  preload="metadata"
362
  >
363
  </audio>
 
1
  <script lang="ts">
2
+ import { onMount, untrack } from "svelte";
3
  import { Music } from "@gradio/icons";
4
  import { format_time, type I18nFormatter } from "@gradio/utils";
5
  import WaveSurfer from "wavesurfer.js";
 
8
  import { Empty } from "@gradio/atoms";
9
  import type { FileData } from "@gradio/client";
10
  import type { WaveformOptions, SubtitleData } from "../shared/types";
 
11
 
12
  import Hls from "hls.js";
13
 
14
+ let {
15
+ value = null,
16
+ subtitles = null,
17
+ label,
18
+ i18n,
19
+ dispatch_blob = () => Promise.resolve(),
20
+ interactive = false,
21
+ editable = true,
22
+ trim_region_settings = {},
23
+ waveform_settings,
24
+ waveform_options,
25
+ mode = $bindable(),
26
+ loop,
27
+ handle_reset_value = () => {},
28
+ playback_position = $bindable(),
29
+ onstop,
30
+ onplay,
31
+ onpause,
32
+ onedit,
33
+ onload
34
+ }: {
35
+ value?: null | FileData;
36
+ subtitles?: null | string | SubtitleData[];
37
+ label: string;
38
+ i18n: I18nFormatter;
39
+ dispatch_blob?: (
40
+ blobs: Uint8Array[] | Blob[],
41
+ event: "stream" | "change" | "stop_recording"
42
+ ) => Promise<void>;
43
+ interactive?: boolean;
44
+ editable?: boolean;
45
+ trim_region_settings?: Record<string, any>;
46
+ waveform_settings: Record<string, any>;
47
+ waveform_options: WaveformOptions;
48
+ mode?: string;
49
+ loop?: boolean;
50
+ handle_reset_value?: () => void;
51
+ playback_position?: number;
52
+ onstop?: () => void;
53
+ onplay?: () => void;
54
+ onpause?: () => void;
55
+ onedit?: () => void;
56
+ onload?: () => void;
57
+ } = $props();
58
+
59
+ let url = $derived(value?.url);
60
+ let old_playback_position = $state(0);
61
 
62
  let container: HTMLDivElement;
63
  let waveform: WaveSurfer | undefined;
64
+ let waveform_ready = $state(false);
65
  let waveform_component_wrapper: HTMLDivElement;
66
+ let playing = $state(false);
67
 
68
  let subtitle_container: HTMLDivElement;
69
 
70
  let timeRef: HTMLTimeElement;
71
  let durationRef: HTMLTimeElement;
72
+ let audio_duration = $state<number>(0);
73
 
74
+ let trimDuration = $state(0);
75
 
76
+ let show_volume_slider = $state(false);
77
  let audio_player: HTMLAudioElement;
78
 
79
  let stream_active = false;
80
+ let subtitles_toggle = $state(true);
81
  let subtitle_event_handlers: (() => void)[] = [];
82
 
83
+ let use_waveform = $derived(
84
+ waveform_options.show_recording_waveform && !value?.is_stream
85
+ );
86
+
87
+ $effect(() => {
88
+ if (
89
+ waveform_ready &&
90
+ old_playback_position !== playback_position &&
91
+ audio_duration
92
+ ) {
93
+ waveform?.seekTo(playback_position / audio_duration);
94
+ old_playback_position = playback_position;
95
+ }
96
+ });
 
 
 
 
 
 
97
 
98
  const create_waveform = (): void => {
99
  waveform = WaveSurfer.create({
100
  container: container,
101
  ...waveform_settings
102
  });
 
103
  if (subtitles && waveform) {
104
  if (subtitles_toggle) {
105
  add_subtitles_to_waveform(waveform, subtitles);
 
108
  }
109
  }
110
 
111
+ waveform?.on("init", () => {
112
+ waveform_ready = true;
113
+ });
 
114
  waveform?.on("decode", (duration: any) => {
115
  audio_duration = duration;
116
  durationRef && (durationRef.textContent = format_time(duration));
 
123
  firstTimeUpdate = false;
124
  return;
125
  }
126
+ playback_position = currentTime;
127
+ old_playback_position = currentTime;
128
  });
129
 
130
  waveform?.on("interaction", () => {
131
  const currentTime = waveform?.getCurrentTime() || 0;
132
  timeRef && (timeRef.textContent = format_time(currentTime));
133
+ playback_position = currentTime;
134
+ old_playback_position = currentTime;
135
  });
136
 
137
  waveform?.on("ready", () => {
 
138
  if (!waveform_settings.autoplay) {
139
  waveform?.stop();
140
  } else {
 
147
  waveform?.play();
148
  } else {
149
  playing = false;
150
+ onstop?.();
151
  }
152
  });
153
  waveform?.on("pause", () => {
154
  playing = false;
155
+ onpause?.();
156
  });
157
  waveform?.on("play", () => {
158
  playing = true;
159
+ onplay?.();
160
  });
161
 
162
  waveform?.on("load", () => {
163
+ onload?.();
164
  });
165
  };
166
 
167
+ $effect(() => {
168
+ if (url && waveform_ready) {
169
+ untrack(() => {
170
+ if (value?.url && waveform) {
171
+ waveform.load(value.url).catch((e) => {
172
+ if (e.name !== "AbortError") {
173
+ console.error("Waveform load error:", e);
174
+ }
175
+ });
176
+ }
177
+ });
178
+ }
179
+ });
180
 
181
  const handle_trim_audio = async (
182
  start: number,
 
184
  ): Promise<void> => {
185
  mode = "";
186
  const decodedData = waveform?.getDecodedData();
187
+ if (decodedData) {
188
+ const trimmedBlob = await process_audio(
189
  decodedData,
190
  start,
191
  end,
192
  waveform_settings.sampleRate
193
+ );
194
+ await dispatch_blob([trimmedBlob], "change");
195
+ }
196
+ onedit?.();
 
 
197
  };
198
 
199
  async function load_audio(data: string): Promise<void> {
 
206
  }
207
  }
208
 
209
+ $effect(() => {
210
+ if (subtitles && waveform) {
211
+ if (subtitles_toggle) {
212
+ add_subtitles_to_waveform(waveform, subtitles);
213
+ } else {
214
+ hide_subtitles();
215
+ }
216
  }
217
+ });
218
 
219
  function load_stream(value: FileData | null): void {
220
  if (!value || !value.is_stream || !value.url) return;
 
260
  }
261
  }
262
 
263
+ $effect(() => {
264
+ if (audio_player && url && waveform_ready && url) {
265
+ load_audio(url);
266
+ }
267
+ });
268
 
269
+ $effect(() => {
270
+ if (audio_player && value?.is_stream) {
271
+ load_stream(value);
272
+ }
273
+ });
274
 
275
  onMount(() => {
276
+ create_waveform();
277
+ const handleKeydown = (e: KeyboardEvent): void => {
278
  if (!waveform || show_volume_slider) return;
279
 
280
  const is_focused_in_waveform =
 
286
  } else if (e.key === "ArrowLeft" && mode !== "edit") {
287
  skip_audio(waveform, -0.1);
288
  }
289
+ };
290
+ window.addEventListener("keydown", handleKeydown);
291
+
292
+ return () => {
293
+ waveform?.destroy();
294
+ window.removeEventListener("keydown", handleKeydown);
295
+ };
296
  });
297
 
298
  async function add_subtitles_to_waveform(
 
392
  class:hidden={use_waveform}
393
  controls
394
  autoplay={waveform_settings.autoplay}
395
+ {onload}
396
  bind:this={audio_player}
397
+ onended={() => onstop?.()}
398
+ onplay={() => onplay?.()}
399
  preload="metadata"
400
  >
401
  </audio>
6.4.0/audio/recorder/AudioRecorder.svelte CHANGED
@@ -1,7 +1,6 @@
1
  <script lang="ts">
2
  import { onMount } from "svelte";
3
  import type { I18nFormatter } from "@gradio/utils";
4
- import { createEventDispatcher } from "svelte";
5
  import WaveSurfer from "wavesurfer.js";
6
  import { skip_audio, process_audio } from "../shared/utils";
7
  import WSRecord from "wavesurfer.js/dist/plugins/record.js";
@@ -11,39 +10,63 @@
11
  import type { WaveformOptions } from "../shared/types";
12
  import { format_time } from "@gradio/utils";
13
 
14
- export let mode: string;
15
- export let i18n: I18nFormatter;
16
- export let dispatch_blob: (
17
- blobs: Uint8Array[] | Blob[],
18
- event: "stream" | "change" | "stop_recording"
19
- ) => Promise<void> | undefined;
20
- export let waveform_settings: Record<string, any>;
21
- export let waveform_options: WaveformOptions = {
22
- show_recording_waveform: true
23
- };
24
- export let handle_reset_value: () => void;
25
- export let editable = true;
26
- export let recording = false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  let micWaveform: WaveSurfer;
29
- let recordingWaveform: WaveSurfer;
30
- let playing = false;
31
 
32
  let recordingContainer: HTMLDivElement;
33
  let microphoneContainer: HTMLDivElement;
34
 
35
- let record: WSRecord;
36
- let recordedAudio: string | null = null;
37
 
38
  // timestamps
39
  let timeRef: HTMLTimeElement;
40
  let durationRef: HTMLTimeElement;
41
- let audio_duration: number;
42
- let seconds = 0;
43
  let interval: NodeJS.Timeout;
44
- let timing = false;
45
  // trimming
46
- let trimDuration = 0;
 
47
 
48
  const start_interval = (): void => {
49
  clearInterval(interval);
@@ -52,21 +75,10 @@
52
  }, 1000);
53
  };
54
 
55
- const dispatch = createEventDispatcher<{
56
- start_recording: undefined;
57
- pause_recording: undefined;
58
- stop_recording: undefined;
59
- stop: undefined;
60
- play: undefined;
61
- pause: undefined;
62
- end: undefined;
63
- edit: undefined;
64
- }>();
65
-
66
  function record_start_callback(): void {
67
  start_interval();
68
  timing = true;
69
- dispatch("start_recording");
70
  if (waveform_options.show_recording_waveform) {
71
  let waveformCanvas = microphoneContainer;
72
  if (waveformCanvas) waveformCanvas.style.display = "block";
@@ -94,37 +106,47 @@
94
  }
95
  }
96
 
97
- $: record?.on("record-resume", () => {
98
- start_interval();
 
 
99
  });
100
 
101
- $: recordingWaveform?.on("decode", (duration: any) => {
102
- audio_duration = duration;
103
- durationRef && (durationRef.textContent = format_time(duration));
 
 
104
  });
105
 
106
- $: recordingWaveform?.on(
107
- "timeupdate",
108
- (currentTime: any) =>
109
- timeRef && (timeRef.textContent = format_time(currentTime))
110
- );
111
-
112
- $: recordingWaveform?.on("pause", () => {
113
- dispatch("pause");
114
- playing = false;
115
  });
116
 
117
- $: recordingWaveform?.on("play", () => {
118
- dispatch("play");
119
- playing = true;
 
 
120
  });
121
 
122
- $: recordingWaveform?.on("finish", () => {
123
- dispatch("stop");
124
- playing = false;
 
 
125
  });
126
 
127
- let record_mounted = false;
 
 
 
 
 
128
 
129
  const create_mic_waveform = (): void => {
130
  if (microphoneContainer) microphoneContainer.innerHTML = "";
@@ -140,7 +162,7 @@
140
  record?.on("record-end", record_end_callback);
141
  record?.on("record-start", record_start_callback);
142
  record?.on("record-pause", () => {
143
- dispatch("pause_recording");
144
  clearInterval(interval);
145
  });
146
 
@@ -174,17 +196,17 @@
174
  end: number
175
  ): Promise<void> => {
176
  mode = "edit";
177
- const decodedData = recordingWaveform.getDecodedData();
178
  if (decodedData)
179
  await process_audio(decodedData, start, end).then(
180
  async (trimmedAudio: Uint8Array) => {
181
  await dispatch_blob([trimmedAudio], "change");
182
  await dispatch_blob([trimmedAudio], "stop_recording");
183
- recordingWaveform.destroy();
184
  create_recording_waveform();
185
  }
186
  );
187
- dispatch("edit");
188
  };
189
 
190
  onMount(() => {
@@ -228,9 +250,9 @@
228
  </div>
229
  {/if}
230
 
231
- {#if microphoneContainer && !recordedAudio && record_mounted}
232
  <WaveformRecordControls
233
- bind:record
234
  {i18n}
235
  {timing}
236
  {recording}
@@ -241,7 +263,7 @@
241
 
242
  {#if recordingWaveform && recordedAudio}
243
  <WaveformControls
244
- bind:waveform={recordingWaveform}
245
  container={recordingContainer}
246
  {playing}
247
  {audio_duration}
 
1
  <script lang="ts">
2
  import { onMount } from "svelte";
3
  import type { I18nFormatter } from "@gradio/utils";
 
4
  import WaveSurfer from "wavesurfer.js";
5
  import { skip_audio, process_audio } from "../shared/utils";
6
  import WSRecord from "wavesurfer.js/dist/plugins/record.js";
 
10
  import type { WaveformOptions } from "../shared/types";
11
  import { format_time } from "@gradio/utils";
12
 
13
+ let {
14
+ mode = $bindable(),
15
+ i18n,
16
+ dispatch_blob,
17
+ waveform_settings,
18
+ waveform_options = { show_recording_waveform: true },
19
+ handle_reset_value,
20
+ editable = true,
21
+ recording = false,
22
+ onstartrecording,
23
+ onpauserecording,
24
+ onstoprecording,
25
+ onstop,
26
+ onplay,
27
+ onpause,
28
+ onedit
29
+ }: {
30
+ mode?: string;
31
+ i18n: I18nFormatter;
32
+ dispatch_blob: (
33
+ blobs: Uint8Array[] | Blob[],
34
+ event: "stream" | "change" | "stop_recording"
35
+ ) => Promise<void> | undefined;
36
+ waveform_settings: Record<string, any>;
37
+ waveform_options?: WaveformOptions;
38
+ handle_reset_value: () => void;
39
+ editable?: boolean;
40
+ recording?: boolean;
41
+ onstartrecording?: () => void;
42
+ onpauserecording?: () => void;
43
+ onstoprecording?: () => void;
44
+ onstop?: () => void;
45
+ onplay?: () => void;
46
+ onpause?: () => void;
47
+ onedit?: () => void;
48
+ } = $props();
49
 
50
  let micWaveform: WaveSurfer;
51
+ let recordingWaveform = $state<WaveSurfer | undefined>(undefined);
52
+ let playing = $state(false);
53
 
54
  let recordingContainer: HTMLDivElement;
55
  let microphoneContainer: HTMLDivElement;
56
 
57
+ let record = $state<WSRecord | undefined>(undefined);
58
+ let recordedAudio = $state<string | null>(null);
59
 
60
  // timestamps
61
  let timeRef: HTMLTimeElement;
62
  let durationRef: HTMLTimeElement;
63
+ let audio_duration = $state(0);
64
+ let seconds = $state(0);
65
  let interval: NodeJS.Timeout;
66
+ let timing = $state(false);
67
  // trimming
68
+ let trimDuration = $state(0);
69
+ let record_mounted = $state(false);
70
 
71
  const start_interval = (): void => {
72
  clearInterval(interval);
 
75
  }, 1000);
76
  };
77
 
 
 
 
 
 
 
 
 
 
 
 
78
  function record_start_callback(): void {
79
  start_interval();
80
  timing = true;
81
+ onstartrecording?.();
82
  if (waveform_options.show_recording_waveform) {
83
  let waveformCanvas = microphoneContainer;
84
  if (waveformCanvas) waveformCanvas.style.display = "block";
 
106
  }
107
  }
108
 
109
+ $effect(() => {
110
+ record?.on("record-resume", () => {
111
+ start_interval();
112
+ });
113
  });
114
 
115
+ $effect(() => {
116
+ recordingWaveform?.on("decode", (duration: any) => {
117
+ audio_duration = duration;
118
+ durationRef && (durationRef.textContent = format_time(duration));
119
+ });
120
  });
121
 
122
+ $effect(() => {
123
+ recordingWaveform?.on(
124
+ "timeupdate",
125
+ (currentTime: any) =>
126
+ timeRef && (timeRef.textContent = format_time(currentTime))
127
+ );
 
 
 
128
  });
129
 
130
+ $effect(() => {
131
+ recordingWaveform?.on("pause", () => {
132
+ onpause?.();
133
+ playing = false;
134
+ });
135
  });
136
 
137
+ $effect(() => {
138
+ recordingWaveform?.on("play", () => {
139
+ onplay?.();
140
+ playing = true;
141
+ });
142
  });
143
 
144
+ $effect(() => {
145
+ recordingWaveform?.on("finish", () => {
146
+ onstop?.();
147
+ playing = false;
148
+ });
149
+ });
150
 
151
  const create_mic_waveform = (): void => {
152
  if (microphoneContainer) microphoneContainer.innerHTML = "";
 
162
  record?.on("record-end", record_end_callback);
163
  record?.on("record-start", record_start_callback);
164
  record?.on("record-pause", () => {
165
+ onpauserecording?.();
166
  clearInterval(interval);
167
  });
168
 
 
196
  end: number
197
  ): Promise<void> => {
198
  mode = "edit";
199
+ const decodedData = recordingWaveform?.getDecodedData();
200
  if (decodedData)
201
  await process_audio(decodedData, start, end).then(
202
  async (trimmedAudio: Uint8Array) => {
203
  await dispatch_blob([trimmedAudio], "change");
204
  await dispatch_blob([trimmedAudio], "stop_recording");
205
+ recordingWaveform?.destroy();
206
  create_recording_waveform();
207
  }
208
  );
209
+ onedit?.();
210
  };
211
 
212
  onMount(() => {
 
250
  </div>
251
  {/if}
252
 
253
+ {#if record_mounted && !recordedAudio}
254
  <WaveformRecordControls
255
+ {record}
256
  {i18n}
257
  {timing}
258
  {recording}
 
263
 
264
  {#if recordingWaveform && recordedAudio}
265
  <WaveformControls
266
+ waveform={recordingWaveform}
267
  container={recordingContainer}
268
  {playing}
269
  {audio_duration}
6.4.0/audio/shared/Audio.svelte CHANGED
@@ -1,20 +1,17 @@
1
  <script lang="ts">
2
  import type { HTMLAudioAttributes } from "svelte/elements";
3
- import { createEventDispatcher } from "svelte";
4
- interface Props extends HTMLAudioAttributes {
5
- "data-testid"?: string;
6
- }
7
- type $$Props = Props;
8
 
9
- export let src: HTMLAudioAttributes["src"] = undefined;
10
-
11
- const dispatch = createEventDispatcher();
 
 
 
 
 
 
 
 
12
  </script>
13
 
14
- <audio
15
- {src}
16
- {...$$restProps}
17
- on:play={dispatch.bind(null, "play")}
18
- on:pause={dispatch.bind(null, "pause")}
19
- on:ended={dispatch.bind(null, "ended")}
20
- />
 
1
  <script lang="ts">
2
  import type { HTMLAudioAttributes } from "svelte/elements";
 
 
 
 
 
3
 
4
+ let {
5
+ src = undefined,
6
+ onplay,
7
+ onpause,
8
+ onended,
9
+ ...restProps
10
+ }: HTMLAudioAttributes & {
11
+ onplay?: () => void;
12
+ onpause?: () => void;
13
+ onended?: () => void;
14
+ } = $props();
15
  </script>
16
 
17
+ <audio {src} {...restProps} {onplay} {onpause} {onended} />
 
 
 
 
 
 
6.4.0/audio/shared/DeviceSelect.svelte CHANGED
@@ -1,20 +1,23 @@
1
  <script lang="ts">
 
2
  import RecordPlugin from "wavesurfer.js/dist/plugins/record.js";
3
  import type { I18nFormatter } from "@gradio/utils";
4
- import { createEventDispatcher } from "svelte";
5
 
6
- export let i18n: I18nFormatter;
7
- export let micDevices: MediaDeviceInfo[] = [];
 
 
 
 
 
 
 
8
 
9
- const dispatch = createEventDispatcher<{
10
- error: string;
11
- }>();
12
-
13
- $: if (typeof window !== "undefined") {
14
- try {
15
  let tempDevices: MediaDeviceInfo[] = [];
16
- RecordPlugin.getAvailableAudioDevices().then(
17
- (devices: MediaDeviceInfo[]) => {
18
  micDevices = devices;
19
  devices.forEach((device) => {
20
  if (device.deviceId) {
@@ -22,23 +25,22 @@
22
  }
23
  });
24
  micDevices = tempDevices;
25
- }
26
- );
27
- } catch (err) {
28
- if (err instanceof DOMException && err.name == "NotAllowedError") {
29
- dispatch("error", i18n("audio.allow_recording_access"));
30
- }
31
- throw err;
32
  }
33
- }
34
  </script>
35
 
36
  <select
37
  class="mic-select"
38
  aria-label="Select input device"
39
- disabled={micDevices.length === 0}
40
  >
41
- {#if micDevices.length === 0}
42
  <option value="">{i18n("audio.no_microphone")}</option>
43
  {:else}
44
  {#each micDevices as micDevice}
 
1
  <script lang="ts">
2
+ import { onMount } from "svelte";
3
  import RecordPlugin from "wavesurfer.js/dist/plugins/record.js";
4
  import type { I18nFormatter } from "@gradio/utils";
 
5
 
6
+ let {
7
+ i18n,
8
+ micDevices = $bindable(),
9
+ onerror
10
+ }: {
11
+ i18n: I18nFormatter;
12
+ micDevices?: MediaDeviceInfo[];
13
+ onerror?: (error: string) => void;
14
+ } = $props();
15
 
16
+ onMount(() => {
17
+ if (typeof window !== "undefined" && navigator.mediaDevices) {
 
 
 
 
18
  let tempDevices: MediaDeviceInfo[] = [];
19
+ RecordPlugin.getAvailableAudioDevices()
20
+ .then((devices: MediaDeviceInfo[]) => {
21
  micDevices = devices;
22
  devices.forEach((device) => {
23
  if (device.deviceId) {
 
25
  }
26
  });
27
  micDevices = tempDevices;
28
+ })
29
+ .catch((err) => {
30
+ if (err instanceof DOMException && err.name == "NotAllowedError") {
31
+ onerror?.(i18n("audio.allow_recording_access"));
32
+ }
33
+ });
 
34
  }
35
+ });
36
  </script>
37
 
38
  <select
39
  class="mic-select"
40
  aria-label="Select input device"
41
+ disabled={!micDevices || micDevices.length === 0}
42
  >
43
+ {#if !micDevices || micDevices.length === 0}
44
  <option value="">{i18n("audio.no_microphone")}</option>
45
  {:else}
46
  {#each micDevices as micDevice}
6.4.0/audio/shared/MinimalAudioPlayer.svelte CHANGED
@@ -4,9 +4,15 @@
4
  import type { FileData } from "@gradio/client";
5
  import { format_time } from "@gradio/utils";
6
 
7
- export let value: FileData;
8
- export let label: string;
9
- export let loop = false;
 
 
 
 
 
 
10
 
11
  let container: HTMLDivElement;
12
  let waveform: WaveSurfer | undefined;
@@ -15,7 +21,7 @@
15
  let currentTime = 0;
16
  let waveform_ready = false;
17
 
18
- $: resolved_src = value.url;
19
 
20
  const create_waveform = async (): Promise<void> => {
21
  if (!container || !resolved_src || waveform_ready) return;
@@ -92,7 +98,7 @@
92
  >
93
  <button
94
  class="play-btn"
95
- on:click={togglePlay}
96
  aria-label={playing ? "Pause" : "Play"}
97
  >
98
  {#if playing}
 
4
  import type { FileData } from "@gradio/client";
5
  import { format_time } from "@gradio/utils";
6
 
7
+ let {
8
+ value,
9
+ label,
10
+ loop = false
11
+ }: {
12
+ value: FileData;
13
+ label: string;
14
+ loop?: boolean;
15
+ } = $props();
16
 
17
  let container: HTMLDivElement;
18
  let waveform: WaveSurfer | undefined;
 
21
  let currentTime = 0;
22
  let waveform_ready = false;
23
 
24
+ let resolved_src = $derived(value.url);
25
 
26
  const create_waveform = async (): Promise<void> => {
27
  if (!container || !resolved_src || waveform_ready) return;
 
98
  >
99
  <button
100
  class="play-btn"
101
+ onclick={togglePlay}
102
  aria-label={playing ? "Pause" : "Play"}
103
  >
104
  {#if playing}
6.4.0/audio/shared/MinimalAudioRecorder.svelte CHANGED
@@ -1,5 +1,5 @@
1
  <script lang="ts">
2
- import { onMount, onDestroy, createEventDispatcher, tick } from "svelte";
3
  import WaveSurfer from "wavesurfer.js";
4
  import RecordPlugin from "wavesurfer.js/dist/plugins/record.js";
5
  import { format_time } from "@gradio/utils";
@@ -7,19 +7,29 @@
7
  import { prepare_files, type FileData, type Client } from "@gradio/client";
8
  import { Square } from "@gradio/icons";
9
 
10
- export let label: string;
11
- export let waveform_settings: Record<string, any> = {};
12
- export let recording = false;
13
- export let upload: Client["upload"];
14
- export let root: string;
15
- export let max_file_size: number | null = null;
16
- export let upload_promise: Promise<any> | null = null;
17
-
18
- const dispatch = createEventDispatcher<{
19
- change: FileData;
20
- stop_recording: undefined;
21
- clear: undefined;
22
- }>();
 
 
 
 
 
 
 
 
 
 
23
 
24
  let container: HTMLDivElement;
25
  let waveform: WaveSurfer | undefined;
@@ -107,13 +117,13 @@
107
  const file_data = uploaded_files?.[0];
108
 
109
  if (file_data) {
110
- dispatch("change", file_data);
111
  }
112
  }
113
  } catch (e) {
114
  console.error("Error processing audio:", e);
115
  } finally {
116
- dispatch("stop_recording");
117
  upload_promise = null;
118
  }
119
  })();
@@ -150,20 +160,22 @@
150
  }
151
  });
152
 
153
- $: if (
154
- recording &&
155
- !is_recording &&
156
- record &&
157
- has_started === false &&
158
- mic_devices.length <= 1
159
- ) {
160
- record.startMic({ deviceId: selected_device_id }).then(() => {
161
- record?.startRecording();
162
- });
163
- } else if (!recording && is_recording && record) {
164
- record.stopRecording();
165
- seconds = 0;
166
- }
 
 
167
 
168
  async function startRecording(): Promise<void> {
169
  show_device_selection = false;
@@ -206,7 +218,7 @@
206
  {/if}
207
  <button
208
  class="record-button"
209
- on:click={startRecording}
210
  aria-label="Start recording"
211
  >
212
  </button>
@@ -216,7 +228,7 @@
216
  <div class="timestamp">{format_time(seconds)}</div>
217
  <button
218
  class="stop-button"
219
- on:click={() => {
220
  recording = false;
221
  }}
222
  aria-label="Stop recording"
 
1
  <script lang="ts">
2
+ import { onMount, onDestroy, tick } from "svelte";
3
  import WaveSurfer from "wavesurfer.js";
4
  import RecordPlugin from "wavesurfer.js/dist/plugins/record.js";
5
  import { format_time } from "@gradio/utils";
 
7
  import { prepare_files, type FileData, type Client } from "@gradio/client";
8
  import { Square } from "@gradio/icons";
9
 
10
+ let {
11
+ label,
12
+ waveform_settings = {},
13
+ recording = $bindable(),
14
+ upload,
15
+ root,
16
+ max_file_size = null,
17
+ upload_promise = $bindable(),
18
+ onchange,
19
+ onstoprecording,
20
+ onclear
21
+ }: {
22
+ label: string;
23
+ waveform_settings?: Record<string, any>;
24
+ recording?: boolean;
25
+ upload: Client["upload"];
26
+ root: string;
27
+ max_file_size?: number | null;
28
+ upload_promise?: Promise<any> | null;
29
+ onchange?: (value: FileData) => void;
30
+ onstoprecording?: () => void;
31
+ onclear?: () => void;
32
+ } = $props();
33
 
34
  let container: HTMLDivElement;
35
  let waveform: WaveSurfer | undefined;
 
117
  const file_data = uploaded_files?.[0];
118
 
119
  if (file_data) {
120
+ onchange?.(file_data);
121
  }
122
  }
123
  } catch (e) {
124
  console.error("Error processing audio:", e);
125
  } finally {
126
+ onstoprecording?.();
127
  upload_promise = null;
128
  }
129
  })();
 
160
  }
161
  });
162
 
163
+ $effect(() => {
164
+ if (
165
+ recording &&
166
+ !is_recording &&
167
+ record &&
168
+ has_started === false &&
169
+ mic_devices.length <= 1
170
+ ) {
171
+ record.startMic({ deviceId: selected_device_id }).then(() => {
172
+ record?.startRecording();
173
+ });
174
+ } else if (!recording && is_recording && record) {
175
+ record.stopRecording();
176
+ seconds = 0;
177
+ }
178
+ });
179
 
180
  async function startRecording(): Promise<void> {
181
  show_device_selection = false;
 
218
  {/if}
219
  <button
220
  class="record-button"
221
+ onclick={startRecording}
222
  aria-label="Start recording"
223
  >
224
  </button>
 
228
  <div class="timestamp">{format_time(seconds)}</div>
229
  <button
230
  class="stop-button"
231
+ onclick={() => {
232
  recording = false;
233
  }}
234
  aria-label="Stop recording"
6.4.0/audio/shared/VolumeControl.svelte CHANGED
@@ -2,9 +2,15 @@
2
  import { onMount } from "svelte";
3
  import WaveSurfer from "wavesurfer.js";
4
 
5
- export let currentVolume = 1;
6
- export let show_volume_slider = false;
7
- export let waveform: WaveSurfer | undefined;
 
 
 
 
 
 
8
 
9
  let volumeElement: HTMLInputElement;
10
 
@@ -21,7 +27,10 @@
21
  }%, var(--neutral-400) ${currentVolume * 100}%)`;
22
  };
23
 
24
- $: (currentVolume, adjustSlider());
 
 
 
25
  </script>
26
 
27
  <input
@@ -33,8 +42,8 @@
33
  max="1"
34
  step="0.01"
35
  value={currentVolume}
36
- on:focusout={() => (show_volume_slider = false)}
37
- on:input={(e) => {
38
  if (e.target instanceof HTMLInputElement) {
39
  currentVolume = parseFloat(e.target.value);
40
  waveform?.setVolume(currentVolume);
 
2
  import { onMount } from "svelte";
3
  import WaveSurfer from "wavesurfer.js";
4
 
5
+ let {
6
+ currentVolume = $bindable(),
7
+ show_volume_slider = $bindable(),
8
+ waveform
9
+ }: {
10
+ currentVolume?: number;
11
+ show_volume_slider?: boolean;
12
+ waveform: WaveSurfer | undefined;
13
+ } = $props();
14
 
15
  let volumeElement: HTMLInputElement;
16
 
 
27
  }%, var(--neutral-400) ${currentVolume * 100}%)`;
28
  };
29
 
30
+ $effect(() => {
31
+ currentVolume;
32
+ adjustSlider();
33
+ });
34
  </script>
35
 
36
  <input
 
42
  max="1"
43
  step="0.01"
44
  value={currentVolume}
45
+ onfocusout={() => (show_volume_slider = false)}
46
+ oninput={(e) => {
47
  if (e.target instanceof HTMLInputElement) {
48
  currentVolume = parseFloat(e.target.value);
49
  waveform?.setVolume(currentVolume);
6.4.0/audio/shared/VolumeLevels.svelte CHANGED
@@ -1,6 +1,7 @@
1
  <script lang="ts">
2
  import { VolumeMuted, VolumeHigh, VolumeLow } from "@gradio/icons";
3
- export let currentVolume: number;
 
4
  </script>
5
 
6
  {#if currentVolume == 0}
 
1
  <script lang="ts">
2
  import { VolumeMuted, VolumeHigh, VolumeLow } from "@gradio/icons";
3
+
4
+ let { currentVolume }: { currentVolume: number } = $props();
5
  </script>
6
 
7
  {#if currentVolume == 0}
6.4.0/audio/shared/WaveformControls.svelte CHANGED
@@ -17,54 +17,101 @@
17
  import type { WaveformOptions } from "./types";
18
  import VolumeLevels from "./VolumeLevels.svelte";
19
  import VolumeControl from "./VolumeControl.svelte";
20
-
21
- export let waveform: WaveSurfer | undefined;
22
- export let audio_duration: number;
23
- export let i18n: I18nFormatter;
24
- export let playing: boolean;
25
- export let show_redo = false;
26
- export let interactive = false;
27
- export let handle_trim_audio: (start: number, end: number) => void;
28
- export let mode = "";
29
- export let container: HTMLDivElement;
30
- export let handle_reset_value: () => void;
31
- export let waveform_options: WaveformOptions = {};
32
- export let trim_region_settings: WaveformOptions = {};
33
- export let show_volume_slider = false;
34
- export let editable = true;
35
- export let subtitles_toggle = true;
36
- export let show_subtitles = false;
37
- export let trimDuration = 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  let playbackSpeeds = [0.5, 1, 1.5, 2];
40
- let playbackSpeed = playbackSpeeds[1];
41
 
42
- let trimRegion: RegionsPlugin | null = null;
43
- let activeRegion: Region | null = null;
44
 
45
- let leftRegionHandle: HTMLDivElement | null;
46
- let rightRegionHandle: HTMLDivElement | null;
47
- let activeHandle = "";
48
 
49
- let currentVolume = 1;
50
 
51
- $: trimRegion =
52
- container && waveform
53
- ? waveform.registerPlugin(RegionsPlugin.create())
54
- : null;
 
 
 
 
 
55
 
56
- $: trimRegion?.on("region-out", (region) => {
57
- region.play();
 
 
 
 
 
 
 
58
  });
59
 
60
- $: trimRegion?.on("region-updated", (region) => {
61
- trimDuration = region.end - region.start;
 
 
 
 
 
 
 
62
  });
63
 
64
- $: trimRegion?.on("region-clicked", (region, e) => {
65
- e.stopPropagation(); // prevent triggering a click on the waveform
66
- activeRegion = region;
67
- region.play();
 
 
 
 
 
 
 
68
  });
69
 
70
  const addTrimRegion = (): void => {
@@ -78,29 +125,37 @@
78
  trimDuration = activeRegion.end - activeRegion.start;
79
  };
80
 
81
- $: if (activeRegion) {
82
- const shadowRoot = container.children[0]!.shadowRoot!;
83
-
84
- rightRegionHandle = shadowRoot.querySelector('[data-resize="right"]');
85
- leftRegionHandle = shadowRoot.querySelector('[data-resize="left"]');
86
-
87
- if (leftRegionHandle && rightRegionHandle) {
88
- leftRegionHandle.setAttribute("role", "button");
89
- rightRegionHandle.setAttribute("role", "button");
90
- leftRegionHandle?.setAttribute("aria-label", "Drag to adjust start time");
91
- rightRegionHandle?.setAttribute("aria-label", "Drag to adjust end time");
92
- leftRegionHandle?.setAttribute("tabindex", "0");
93
- rightRegionHandle?.setAttribute("tabindex", "0");
94
-
95
- leftRegionHandle.addEventListener("focus", () => {
96
- if (trimRegion) activeHandle = "left";
97
- });
98
-
99
- rightRegionHandle.addEventListener("focus", () => {
100
- if (trimRegion) activeHandle = "right";
101
- });
 
 
 
 
 
 
 
 
102
  }
103
- }
104
 
105
  const trimAudio = (): void => {
106
  if (waveform && trimRegion) {
@@ -123,10 +178,11 @@
123
 
124
  const toggleTrimmingMode = (): void => {
125
  clearRegions();
126
- if (mode === "edit") {
127
  mode = "";
128
  } else {
129
  mode = "edit";
 
130
  addTrimRegion();
131
  }
132
  };
@@ -166,14 +222,21 @@
166
  trimDuration = activeRegion.end - activeRegion.start;
167
  };
168
 
169
- $: trimRegion &&
170
- window.addEventListener("keydown", (e) => {
171
- if (e.key === "ArrowLeft") {
172
- adjustRegionHandles(activeHandle, "ArrowLeft");
173
- } else if (e.key === "ArrowRight") {
174
- adjustRegionHandles(activeHandle, "ArrowRight");
175
- }
176
- });
 
 
 
 
 
 
 
177
  </script>
178
 
179
  <div class="controls" data-testid="waveform-controls">
@@ -184,7 +247,7 @@
184
  ? "var(--color-accent)"
185
  : "var(--neutral-400)"}
186
  aria-label="Adjust volume"
187
- on:click={() => (show_volume_slider = !show_volume_slider)}
188
  >
189
  <VolumeLevels {currentVolume} />
190
  </button>
@@ -201,7 +264,7 @@
201
  (playbackSpeeds.indexOf(playbackSpeed) + 1) % playbackSpeeds.length
202
  ]
203
  }x`}
204
- on:click={() => {
205
  playbackSpeed =
206
  playbackSpeeds[
207
  (playbackSpeeds.indexOf(playbackSpeed) + 1) % playbackSpeeds.length
@@ -221,7 +284,7 @@
221
  audio_duration,
222
  waveform_options.skip_length
223
  )} seconds`}
224
- on:click={() =>
225
  waveform?.skip(
226
  get_skip_rewind_amount(audio_duration, waveform_options.skip_length) *
227
  -1
@@ -231,7 +294,7 @@
231
  </button>
232
  <button
233
  class="play-pause-button icon"
234
- on:click={() => waveform?.playPause()}
235
  aria-label={playing ? i18n("audio.pause") : i18n("audio.play")}
236
  >
237
  {#if playing}
@@ -246,7 +309,7 @@
246
  audio_duration,
247
  waveform_options.skip_length
248
  )} seconds"
249
- on:click={() =>
250
  waveform?.skip(
251
  get_skip_rewind_amount(audio_duration, waveform_options.skip_length)
252
  )}
@@ -263,17 +326,17 @@
263
  style="color: {subtitles_toggle
264
  ? 'var(--color-accent)'
265
  : 'var(--neutral-400)'}"
266
- on:click={toggleSubtitles}
267
  >
268
  <ClosedCaption /></button
269
  >
270
  {/if}
271
  {#if editable && interactive}
272
- {#if show_redo && mode === ""}
273
  <button
274
  class="action icon"
275
  aria-label="Reset audio"
276
- on:click={() => {
277
  handle_reset_value();
278
  clearRegions();
279
  mode = "";
@@ -283,18 +346,17 @@
283
  </button>
284
  {/if}
285
 
286
- {#if mode === ""}
287
  <button
288
  class="action icon"
289
  aria-label="Trim audio to selection"
290
- on:click={toggleTrimmingMode}
291
  >
292
  <Trim />
293
  </button>
294
  {:else}
295
- <button class="text-button" on:click={trimAudio}>Trim</button>
296
- <button class="text-button" on:click={toggleTrimmingMode}>Cancel</button
297
- >
298
  {/if}
299
  {/if}
300
  </div>
 
17
  import type { WaveformOptions } from "./types";
18
  import VolumeLevels from "./VolumeLevels.svelte";
19
  import VolumeControl from "./VolumeControl.svelte";
20
+ import { onMount } from "svelte";
21
+
22
+ let {
23
+ waveform,
24
+ audio_duration,
25
+ i18n,
26
+ playing,
27
+ show_redo = false,
28
+ interactive = false,
29
+ handle_trim_audio,
30
+ mode = $bindable(),
31
+ container,
32
+ handle_reset_value,
33
+ waveform_options = {},
34
+ trim_region_settings = {},
35
+ show_volume_slider = $bindable(),
36
+ editable = true,
37
+ subtitles_toggle = $bindable(),
38
+ show_subtitles = false,
39
+ trimDuration = $bindable()
40
+ }: {
41
+ waveform: WaveSurfer | undefined;
42
+ audio_duration: number;
43
+ i18n: I18nFormatter;
44
+ playing: boolean;
45
+ show_redo?: boolean;
46
+ interactive?: boolean;
47
+ handle_trim_audio: (start: number, end: number) => void;
48
+ mode?: string;
49
+ container: HTMLDivElement;
50
+ handle_reset_value: () => void;
51
+ waveform_options?: WaveformOptions;
52
+ trim_region_settings?: WaveformOptions;
53
+ show_volume_slider?: boolean;
54
+ editable?: boolean;
55
+ subtitles_toggle?: boolean;
56
+ show_subtitles?: boolean;
57
+ trimDuration?: number;
58
+ } = $props();
59
 
60
  let playbackSpeeds = [0.5, 1, 1.5, 2];
61
+ let playbackSpeed = $state(playbackSpeeds[1]);
62
 
63
+ let trimRegion: RegionsPlugin | null = $state(null);
64
+ let activeRegion: Region | null = $state(null);
65
 
66
+ let leftRegionHandle: HTMLDivElement | null = $state(null);
67
+ let rightRegionHandle: HTMLDivElement | null = $state(null);
68
+ let activeHandle = $state("");
69
 
70
+ let currentVolume = $state(1);
71
 
72
+ function ensureTrimRegion(): void {
73
+ if (container && waveform && !trimRegion) {
74
+ trimRegion = waveform.registerPlugin(RegionsPlugin.create());
75
+ }
76
+ }
77
+
78
+ onMount(() => {
79
+ ensureTrimRegion();
80
+ });
81
 
82
+ $effect(() => {
83
+ if (!trimRegion) return;
84
+ const handler = (region: Region): void => {
85
+ region.play();
86
+ };
87
+ trimRegion.on("region-out", handler);
88
+ return () => {
89
+ trimRegion?.un("region-out", handler);
90
+ };
91
  });
92
 
93
+ $effect(() => {
94
+ if (!trimRegion) return;
95
+ const handler = (region: Region): void => {
96
+ trimDuration = region.end - region.start;
97
+ };
98
+ trimRegion.on("region-updated", handler);
99
+ return () => {
100
+ trimRegion?.un("region-updated", handler);
101
+ };
102
  });
103
 
104
+ $effect(() => {
105
+ if (!trimRegion) return;
106
+ const handler = (region: Region, e: Event): void => {
107
+ e.stopPropagation();
108
+ activeRegion = region;
109
+ region.play();
110
+ };
111
+ trimRegion.on("region-clicked", handler);
112
+ return () => {
113
+ trimRegion?.un("region-clicked", handler);
114
+ };
115
  });
116
 
117
  const addTrimRegion = (): void => {
 
125
  trimDuration = activeRegion.end - activeRegion.start;
126
  };
127
 
128
+ $effect(() => {
129
+ if (activeRegion) {
130
+ const shadowRoot = container.children[0]!.shadowRoot!;
131
+
132
+ rightRegionHandle = shadowRoot.querySelector('[data-resize="right"]');
133
+ leftRegionHandle = shadowRoot.querySelector('[data-resize="left"]');
134
+
135
+ if (leftRegionHandle && rightRegionHandle) {
136
+ leftRegionHandle.setAttribute("role", "button");
137
+ rightRegionHandle.setAttribute("role", "button");
138
+ leftRegionHandle?.setAttribute(
139
+ "aria-label",
140
+ "Drag to adjust start time"
141
+ );
142
+ rightRegionHandle?.setAttribute(
143
+ "aria-label",
144
+ "Drag to adjust end time"
145
+ );
146
+ leftRegionHandle?.setAttribute("tabindex", "0");
147
+ rightRegionHandle?.setAttribute("tabindex", "0");
148
+
149
+ leftRegionHandle.addEventListener("focus", () => {
150
+ if (trimRegion) activeHandle = "left";
151
+ });
152
+
153
+ rightRegionHandle.addEventListener("focus", () => {
154
+ if (trimRegion) activeHandle = "right";
155
+ });
156
+ }
157
  }
158
+ });
159
 
160
  const trimAudio = (): void => {
161
  if (waveform && trimRegion) {
 
178
 
179
  const toggleTrimmingMode = (): void => {
180
  clearRegions();
181
+ if (mode) {
182
  mode = "";
183
  } else {
184
  mode = "edit";
185
+ ensureTrimRegion();
186
  addTrimRegion();
187
  }
188
  };
 
222
  trimDuration = activeRegion.end - activeRegion.start;
223
  };
224
 
225
+ $effect(() => {
226
+ if (trimRegion) {
227
+ const handleKeydown = (e: KeyboardEvent): void => {
228
+ if (e.key === "ArrowLeft") {
229
+ adjustRegionHandles(activeHandle, "ArrowLeft");
230
+ } else if (e.key === "ArrowRight") {
231
+ adjustRegionHandles(activeHandle, "ArrowRight");
232
+ }
233
+ };
234
+ window.addEventListener("keydown", handleKeydown);
235
+ return () => {
236
+ window.removeEventListener("keydown", handleKeydown);
237
+ };
238
+ }
239
+ });
240
  </script>
241
 
242
  <div class="controls" data-testid="waveform-controls">
 
247
  ? "var(--color-accent)"
248
  : "var(--neutral-400)"}
249
  aria-label="Adjust volume"
250
+ onclick={() => (show_volume_slider = !show_volume_slider)}
251
  >
252
  <VolumeLevels {currentVolume} />
253
  </button>
 
264
  (playbackSpeeds.indexOf(playbackSpeed) + 1) % playbackSpeeds.length
265
  ]
266
  }x`}
267
+ onclick={() => {
268
  playbackSpeed =
269
  playbackSpeeds[
270
  (playbackSpeeds.indexOf(playbackSpeed) + 1) % playbackSpeeds.length
 
284
  audio_duration,
285
  waveform_options.skip_length
286
  )} seconds`}
287
+ onclick={() =>
288
  waveform?.skip(
289
  get_skip_rewind_amount(audio_duration, waveform_options.skip_length) *
290
  -1
 
294
  </button>
295
  <button
296
  class="play-pause-button icon"
297
+ onclick={() => waveform?.playPause()}
298
  aria-label={playing ? i18n("audio.pause") : i18n("audio.play")}
299
  >
300
  {#if playing}
 
309
  audio_duration,
310
  waveform_options.skip_length
311
  )} seconds"
312
+ onclick={() =>
313
  waveform?.skip(
314
  get_skip_rewind_amount(audio_duration, waveform_options.skip_length)
315
  )}
 
326
  style="color: {subtitles_toggle
327
  ? 'var(--color-accent)'
328
  : 'var(--neutral-400)'}"
329
+ onclick={toggleSubtitles}
330
  >
331
  <ClosedCaption /></button
332
  >
333
  {/if}
334
  {#if editable && interactive}
335
+ {#if show_redo && !mode}
336
  <button
337
  class="action icon"
338
  aria-label="Reset audio"
339
+ onclick={() => {
340
  handle_reset_value();
341
  clearRegions();
342
  mode = "";
 
346
  </button>
347
  {/if}
348
 
349
+ {#if !mode}
350
  <button
351
  class="action icon"
352
  aria-label="Trim audio to selection"
353
+ onclick={toggleTrimmingMode}
354
  >
355
  <Trim />
356
  </button>
357
  {:else}
358
+ <button class="text-button" onclick={trimAudio}>Trim</button>
359
+ <button class="text-button" onclick={toggleTrimmingMode}>Cancel</button>
 
360
  {/if}
361
  {/if}
362
  </div>
6.4.0/audio/shared/WaveformRecordControls.svelte CHANGED
@@ -5,21 +5,29 @@
5
  import RecordPlugin from "wavesurfer.js/dist/plugins/record.js";
6
  import DeviceSelect from "./DeviceSelect.svelte";
7
 
8
- export let record: RecordPlugin;
9
- export let i18n: I18nFormatter;
10
- export let recording = false;
11
-
12
- let micDevices: MediaDeviceInfo[] = [];
 
 
 
 
 
 
 
 
 
 
 
 
13
  let recordButton: HTMLButtonElement;
14
  let pauseButton: HTMLButtonElement;
15
  let resumeButton: HTMLButtonElement;
16
  let stopButton: HTMLButtonElement;
17
  let stopButtonPaused: HTMLButtonElement;
18
- let recording_ongoing = false;
19
-
20
- export let record_time: string;
21
- export let show_recording_waveform: boolean | undefined;
22
- export let timing = false;
23
 
24
  const handleRecordStart = (): void => {
25
  recordButton.style.display = "none";
@@ -69,18 +77,20 @@
69
  record.un("record-resume", handleRecordResume);
70
  });
71
 
72
- $: if (recording && !recording_ongoing) {
73
- record.startMic().then(() => {
74
- record.startRecording();
75
- recording_ongoing = true;
76
- });
77
- } else if (!recording && recording_ongoing) {
78
- if (record.isPaused()) {
79
- record.resumeRecording();
 
 
 
 
80
  }
81
- record.stopRecording();
82
- recording_ongoing = false;
83
- }
84
  </script>
85
 
86
  <div class="controls">
@@ -88,13 +98,13 @@
88
  <button
89
  bind:this={recordButton}
90
  class="record record-button"
91
- on:click={() => record.startRecording()}>{i18n("audio.record")}</button
92
  >
93
 
94
  <button
95
  bind:this={stopButton}
96
  class="stop-button {record.isPaused() ? 'stop-button-paused' : ''}"
97
- on:click={() => {
98
  if (record.isPaused()) {
99
  record.resumeRecording();
100
  record.stopRecording();
@@ -108,7 +118,7 @@
108
  bind:this={stopButtonPaused}
109
  id="stop-paused"
110
  class="stop-button-paused"
111
- on:click={() => {
112
  if (record.isPaused()) {
113
  record.resumeRecording();
114
  record.stopRecording();
@@ -122,12 +132,12 @@
122
  aria-label="pause"
123
  bind:this={pauseButton}
124
  class="pause-button"
125
- on:click={() => record.pauseRecording()}><Pause /></button
126
  >
127
  <button
128
  bind:this={resumeButton}
129
  class="resume-button"
130
- on:click={() => record.resumeRecording()}>{i18n("audio.resume")}</button
131
  >
132
  {#if timing && !show_recording_waveform}
133
  <time class="duration-button duration">{record_time}</time>
 
5
  import RecordPlugin from "wavesurfer.js/dist/plugins/record.js";
6
  import DeviceSelect from "./DeviceSelect.svelte";
7
 
8
+ let {
9
+ record,
10
+ i18n,
11
+ recording = false,
12
+ record_time,
13
+ show_recording_waveform,
14
+ timing = false
15
+ }: {
16
+ record: RecordPlugin;
17
+ i18n: I18nFormatter;
18
+ recording?: boolean;
19
+ record_time: string;
20
+ show_recording_waveform: boolean | undefined;
21
+ timing?: boolean;
22
+ } = $props();
23
+
24
+ let micDevices: MediaDeviceInfo[] = $state([]);
25
  let recordButton: HTMLButtonElement;
26
  let pauseButton: HTMLButtonElement;
27
  let resumeButton: HTMLButtonElement;
28
  let stopButton: HTMLButtonElement;
29
  let stopButtonPaused: HTMLButtonElement;
30
+ let recording_ongoing = $state(false);
 
 
 
 
31
 
32
  const handleRecordStart = (): void => {
33
  recordButton.style.display = "none";
 
77
  record.un("record-resume", handleRecordResume);
78
  });
79
 
80
+ $effect(() => {
81
+ if (recording && !recording_ongoing) {
82
+ record.startMic().then(() => {
83
+ record.startRecording();
84
+ recording_ongoing = true;
85
+ });
86
+ } else if (!recording && recording_ongoing) {
87
+ if (record.isPaused()) {
88
+ record.resumeRecording();
89
+ }
90
+ record.stopRecording();
91
+ recording_ongoing = false;
92
  }
93
+ });
 
 
94
  </script>
95
 
96
  <div class="controls">
 
98
  <button
99
  bind:this={recordButton}
100
  class="record record-button"
101
+ onclick={() => record.startRecording()}>{i18n("audio.record")}</button
102
  >
103
 
104
  <button
105
  bind:this={stopButton}
106
  class="stop-button {record.isPaused() ? 'stop-button-paused' : ''}"
107
+ onclick={() => {
108
  if (record.isPaused()) {
109
  record.resumeRecording();
110
  record.stopRecording();
 
118
  bind:this={stopButtonPaused}
119
  id="stop-paused"
120
  class="stop-button-paused"
121
+ onclick={() => {
122
  if (record.isPaused()) {
123
  record.resumeRecording();
124
  record.stopRecording();
 
132
  aria-label="pause"
133
  bind:this={pauseButton}
134
  class="pause-button"
135
+ onclick={() => record.pauseRecording()}><Pause /></button
136
  >
137
  <button
138
  bind:this={resumeButton}
139
  class="resume-button"
140
+ onclick={() => record.resumeRecording()}>{i18n("audio.resume")}</button
141
  >
142
  {#if timing && !show_recording_waveform}
143
  <time class="duration-button duration">{record_time}</time>
6.4.0/audio/shared/types.ts CHANGED
@@ -57,5 +57,6 @@ export interface AudioEvents {
57
  clear_status: any;
58
  close_stream: any;
59
  edit: any;
 
60
  custom_button_click: { id: number };
61
  }
 
57
  clear_status: any;
58
  close_stream: any;
59
  edit: any;
60
+ share: any;
61
  custom_button_click: { id: number };
62
  }
6.4.0/audio/static/StaticAudio.svelte CHANGED
@@ -13,36 +13,58 @@
13
  import type { I18nFormatter } from "@gradio/utils";
14
  import AudioPlayer from "../player/AudioPlayer.svelte";
15
  import MinimalAudioPlayer from "../shared/MinimalAudioPlayer.svelte";
16
- import { createEventDispatcher } from "svelte";
17
  import type { FileData } from "@gradio/client";
18
  import type { WaveformOptions, SubtitleData } from "../shared/types";
19
 
20
- export let value: null | FileData = null;
21
- export let subtitles: null | FileData | SubtitleData[] = null;
22
- export let label: string;
23
- export let show_label = true;
24
- export let buttons: (string | CustomButtonType)[] = [];
25
- export let on_custom_button_click: ((id: number) => void) | null = null;
26
- export let i18n: I18nFormatter;
27
- export let waveform_settings: Record<string, any> = {};
28
- export let waveform_options: WaveformOptions = {
29
- show_recording_waveform: true
30
- };
31
- export let editable = true;
32
- export let loop: boolean;
33
- export let display_icon_button_wrapper_top_corner = false;
34
- export let minimal = false;
35
- export let playback_position = 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- const dispatch = createEventDispatcher<{
38
- change: FileData;
39
- play: undefined;
40
- pause: undefined;
41
- end: undefined;
42
- stop: undefined;
43
- }>();
44
-
45
- $: value && dispatch("change", value);
46
  </script>
47
 
48
  <BlockLabel
@@ -74,11 +96,11 @@
74
  {#if buttons.some((btn) => typeof btn === "string" && btn === "share")}
75
  <ShareButton
76
  {i18n}
77
- on:error
78
- on:share
79
- formatter={async (value) => {
80
- if (!value) return "";
81
- let url = await uploadToHuggingFace(value.url, "url");
82
  return `<audio controls src="${url}"></audio>`;
83
  }}
84
  {value}
@@ -96,10 +118,10 @@
96
  {editable}
97
  {loop}
98
  bind:playback_position
99
- on:pause
100
- on:play
101
- on:stop
102
- on:load
103
  />
104
  {/if}
105
  {:else}
 
13
  import type { I18nFormatter } from "@gradio/utils";
14
  import AudioPlayer from "../player/AudioPlayer.svelte";
15
  import MinimalAudioPlayer from "../shared/MinimalAudioPlayer.svelte";
 
16
  import type { FileData } from "@gradio/client";
17
  import type { WaveformOptions, SubtitleData } from "../shared/types";
18
 
19
+ let {
20
+ value = null,
21
+ subtitles = null,
22
+ label,
23
+ show_label = true,
24
+ buttons = [],
25
+ on_custom_button_click = null,
26
+ i18n,
27
+ waveform_settings = {},
28
+ waveform_options = { show_recording_waveform: true },
29
+ editable = true,
30
+ loop,
31
+ display_icon_button_wrapper_top_corner = false,
32
+ minimal = false,
33
+ playback_position = $bindable(),
34
+ onchange,
35
+ onplay,
36
+ onpause,
37
+ onstop,
38
+ onshare,
39
+ onerror
40
+ }: {
41
+ value?: null | FileData;
42
+ subtitles?: null | FileData | SubtitleData[];
43
+ label: string;
44
+ show_label?: boolean;
45
+ buttons?: (string | CustomButtonType)[];
46
+ on_custom_button_click?: ((id: number) => void) | null;
47
+ i18n: I18nFormatter;
48
+ waveform_settings?: Record<string, any>;
49
+ waveform_options?: WaveformOptions;
50
+ editable?: boolean;
51
+ loop?: boolean;
52
+ display_icon_button_wrapper_top_corner?: boolean;
53
+ minimal?: boolean;
54
+ playback_position?: number;
55
+ onchange?: (value: FileData) => void;
56
+ onplay?: () => void;
57
+ onpause?: () => void;
58
+ onstop?: () => void;
59
+ onshare?: (detail: any) => void;
60
+ onerror?: (detail: any) => void;
61
+ } = $props();
62
 
63
+ $effect(() => {
64
+ if (value) {
65
+ onchange?.(value);
66
+ }
67
+ });
 
 
 
 
68
  </script>
69
 
70
  <BlockLabel
 
96
  {#if buttons.some((btn) => typeof btn === "string" && btn === "share")}
97
  <ShareButton
98
  {i18n}
99
+ {onerror}
100
+ {onshare}
101
+ formatter={async (fileData: FileData) => {
102
+ if (!fileData || !fileData.url) return "";
103
+ let url = await uploadToHuggingFace(fileData.url, "url");
104
  return `<audio controls src="${url}"></audio>`;
105
  }}
106
  {value}
 
118
  {editable}
119
  {loop}
120
  bind:playback_position
121
+ {onpause}
122
+ {onplay}
123
+ {onstop}
124
+ onload={() => {}}
125
  />
126
  {/if}
127
  {:else}
6.4.0/audio/streaming/StreamAudio.svelte CHANGED
@@ -7,23 +7,32 @@
7
  import type { WaveformOptions } from "../shared/types";
8
  import DeviceSelect from "../shared/DeviceSelect.svelte";
9
 
10
- export let recording = false;
11
- export let paused_recording = false;
12
- export let stop: () => void;
13
- export let record: () => void;
14
- export let i18n: I18nFormatter;
15
- export let waveform_settings: Record<string, any>;
16
- export let waveform_options: WaveformOptions = {
17
- show_recording_waveform: true
18
- };
19
- export let waiting = false;
 
 
 
 
 
 
 
 
 
20
 
21
  let micWaveform: WaveSurfer;
22
  let waveformRecord: RecordPlugin;
23
 
24
  let microphoneContainer: HTMLDivElement;
25
 
26
- let micDevices: MediaDeviceInfo[] = [];
27
 
28
  onMount(() => {
29
  create_mic_waveform();
@@ -53,7 +62,7 @@
53
  {#if recording && !waiting}
54
  <button
55
  class={paused_recording ? "stop-button-paused" : "stop-button"}
56
- on:click={() => {
57
  waveformRecord?.stopMic();
58
  stop();
59
  }}
@@ -67,7 +76,7 @@
67
  {:else if recording && waiting}
68
  <button
69
  class="spinner-button"
70
- on:click={() => {
71
  stop();
72
  }}
73
  >
@@ -79,7 +88,7 @@
79
  {:else}
80
  <button
81
  class="record-button"
82
- on:click={() => {
83
  waveformRecord?.startMic();
84
  record();
85
  }}
 
7
  import type { WaveformOptions } from "../shared/types";
8
  import DeviceSelect from "../shared/DeviceSelect.svelte";
9
 
10
+ let {
11
+ recording = false,
12
+ paused_recording = false,
13
+ stop,
14
+ record,
15
+ i18n,
16
+ waveform_settings,
17
+ waveform_options = { show_recording_waveform: true },
18
+ waiting = false
19
+ }: {
20
+ recording?: boolean;
21
+ paused_recording?: boolean;
22
+ stop: () => void;
23
+ record: () => void;
24
+ i18n: I18nFormatter;
25
+ waveform_settings: Record<string, any>;
26
+ waveform_options?: WaveformOptions;
27
+ waiting?: boolean;
28
+ } = $props();
29
 
30
  let micWaveform: WaveSurfer;
31
  let waveformRecord: RecordPlugin;
32
 
33
  let microphoneContainer: HTMLDivElement;
34
 
35
+ let micDevices: MediaDeviceInfo[] = $state([]);
36
 
37
  onMount(() => {
38
  create_mic_waveform();
 
62
  {#if recording && !waiting}
63
  <button
64
  class={paused_recording ? "stop-button-paused" : "stop-button"}
65
+ onclick={() => {
66
  waveformRecord?.stopMic();
67
  stop();
68
  }}
 
76
  {:else if recording && waiting}
77
  <button
78
  class="spinner-button"
79
+ onclick={() => {
80
  stop();
81
  }}
82
  >
 
88
  {:else}
89
  <button
90
  class="record-button"
91
+ onclick={() => {
92
  waveformRecord?.startMic();
93
  record();
94
  }}