Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: mo.ui.microphone to record audio and mo.audio to play audio (#54)

Myles Scolnick74e7fc9968f5
diff --git a/docs/api/index.md b/docs/api/index.md
index 92a6b81365..04594ebe52 100644
--- a/docs/api/index.md
+++ b/docs/api/index.md
@@ -8,6 +8,7 @@
markdown
inputs/index
layouts/index
+ media/index
html
misc
```
@@ -23,5 +24,6 @@ markdown and tabs.
| {doc}`markdown` | Write markdown with `mo.md` |
| {doc}`inputs/index` | Seamlessly connect sliders, dropdowns, tables, and more to Python |
| {doc}`layouts/index` | Customize outputs with accordions, tabs, stacks, and more |
+| {doc}`media/index` | Output media like images and audio |
| {doc}`html` | Working with HTML objects |
| {doc}`misc` | Miscellaneous utilities |
diff --git a/docs/api/inputs/index.md b/docs/api/inputs/index.md
index b5f276eeee..1601a758d1 100644
--- a/docs/api/inputs/index.md
+++ b/docs/api/inputs/index.md
@@ -41,6 +41,7 @@ powerful notebooks and apps. These elements are available in `marimo.ui`.
marimo.ui.dropdown
marimo.ui.file
marimo.ui.form
+ marimo.ui.microphone
marimo.ui.multiselect
marimo.ui.number
marimo.ui.radio
diff --git a/docs/api/inputs/microphone.md b/docs/api/inputs/microphone.md
new file mode 100644
index 0000000000..4b8e3095ba
--- /dev/null
+++ b/docs/api/inputs/microphone.md
@@ -0,0 +1,12 @@
+# Microphone
+
+<!-- TODO: add interactive mo.ui.microphone doc.
+At the moment, our components app uses released versions of marimo, so these changes will lag behind. -->
+<!-- <iframe class="demo" src="https://components.marimo.io/?component=microphone" frameborder="no"></iframe> -->
+
+```{eval-rst}
+.. autoclass:: marimo.ui.microphone
+ :members:
+
+ .. autoclasstoc:: marimo._plugins.ui._impl.microphone.microphone
+```
diff --git a/docs/api/layouts/index.md b/docs/api/layouts/index.md
index 07fc3b5415..dc3c8690be 100644
--- a/docs/api/layouts/index.md
+++ b/docs/api/layouts/index.md
@@ -23,7 +23,6 @@ certain way.
marimo.accordion
marimo.callout
- marimo.image
marimo.hstack
marimo.vstack
marimo.tabs
diff --git a/docs/api/media/audio.md b/docs/api/media/audio.md
new file mode 100644
index 0000000000..390b722141
--- /dev/null
+++ b/docs/api/media/audio.md
@@ -0,0 +1,9 @@
+# Audio
+
+<!-- TODO: add interactive marimo.audio doc.
+At the moment, our components app uses released versions of marimo, so these changes will lag behind. -->
+<!-- <iframe class="demo" src="https://components.marimo.io/?component=refresh" frameborder="no"></iframe> -->
+
+```{eval-rst}
+.. autofunction:: marimo.audio
+```
diff --git a/docs/api/layouts/image.md b/docs/api/media/image.md
similarity index 100%
rename from docs/api/layouts/image.md
rename to docs/api/media/image.md
diff --git a/docs/api/media/index.md b/docs/api/media/index.md
new file mode 100644
index 0000000000..d45172a47f
--- /dev/null
+++ b/docs/api/media/index.md
@@ -0,0 +1,11 @@
+# Media
+
+Use `mo.image` and `mo.audio` to embed images and audio in your outputs.
+
+```{eval-rst}
+.. autosummary::
+ :nosignatures:
+
+ marimo.image
+ marimo.audio
+```
diff --git a/frontend/src/components/audio/audio-recorder.tsx b/frontend/src/components/audio/audio-recorder.tsx
new file mode 100644
index 0000000000..e9389d88f9
--- /dev/null
+++ b/frontend/src/components/audio/audio-recorder.tsx
@@ -0,0 +1,52 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { cn } from "@/lib/utils";
+import React from "react";
+import { Button } from "../ui/button";
+import { CircleIcon, SquareIcon } from "lucide-react";
+import { RecordingStatus } from "@/hooks/useAudioRecorder";
+
+interface AudioRecorderProps {
+ onStart: () => void;
+ onStop: () => void;
+ onPause: () => void;
+ status: RecordingStatus;
+ time?: string;
+}
+
+export const AudioRecorder: React.FC<AudioRecorderProps> = ({
+ onStart,
+ onStop,
+ onPause,
+ status,
+ time,
+}) => {
+ return (
+ <div className="flex items-center gap-3">
+ {status === "stopped" && (
+ <Button variant="secondary" onClick={onStart} className="w-[50px]">
+ <CircleIcon
+ className={cn("w-6 h-6 border border-input rounded-full")}
+ strokeWidth={1.5}
+ fill="var(--red-9)"
+ />
+ </Button>
+ )}
+ {status === "recording" && (
+ <Button variant="secondary" onClick={onStop} className="w-[50px]">
+ <SquareIcon
+ className="w-5 h-5 rounded-sm"
+ fill="var(--red-9)"
+ strokeWidth={1.5}
+ />
+ <CircleIcon
+ className={cn("w-6 h-6 absolute opacity-20 animate-ping")}
+ fill="var(--red-9)"
+ style={{ animationDuration: "1.5s" }}
+ strokeWidth={0}
+ />
+ </Button>
+ )}
+ {time && <span className="text-sm font-bold">{time}s</span>}
+ </div>
+ );
+};
diff --git a/frontend/src/hooks/useAudioRecorder.ts b/frontend/src/hooks/useAudioRecorder.ts
new file mode 100644
index 0000000000..88485fe0ea
--- /dev/null
+++ b/frontend/src/hooks/useAudioRecorder.ts
@@ -0,0 +1,91 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { useState, useRef, useEffect } from "react";
+import { useTimer } from "./useTimer";
+import useEvent from "react-use-event-hook";
+import { Logger } from "@/utils/Logger";
+
+export type RecordingStatus = "recording" | "paused" | "stopped";
+
+export function useAudioRecorder(opts: {
+ onDone?: (blob: Blob) => void;
+ options?: MediaRecorderOptions;
+}) {
+ const { onDone, options } = opts;
+
+ const [recordingStatus, setRecordingStatus] =
+ useState<RecordingStatus>("stopped");
+ const mediaRecorder = useRef<MediaRecorder>();
+ const [allowed, setAllowed] = useState<boolean>(true);
+ const [recordingBlob, setRecordingBlob] = useState<Blob>();
+
+ const timer = useTimer();
+
+ const start: () => void = useEvent(() => {
+ timer.clear();
+
+ navigator.mediaDevices
+ .getUserMedia({ audio: true })
+ .then((stream) => {
+ const recorder = new MediaRecorder(stream, options);
+ setRecordingStatus("recording");
+ mediaRecorder.current = recorder;
+
+ recorder.start();
+ timer.start();
+
+ recorder.addEventListener("dataavailable", (event) => {
+ setRecordingBlob(event.data);
+ onDone?.(event.data);
+ recorder.stream.getTracks().forEach((t) => t.stop());
+ mediaRecorder.current = undefined;
+ });
+ })
+ .catch((error: DOMException) => {
+ Logger.log(error);
+ setAllowed(false);
+ });
+ });
+
+ const stop: () => void = useEvent(() => {
+ mediaRecorder.current?.stop();
+ timer.stop();
+ setRecordingStatus("stopped");
+ });
+
+ const pauseResume = useEvent(() => {
+ setRecordingStatus((state) => {
+ if (state === "recording") {
+ mediaRecorder.current?.pause();
+ timer.stop();
+ return "paused";
+ } else if (state === "paused") {
+ mediaRecorder.current?.resume();
+ timer.start();
+ return "recording";
+ } else {
+ return state;
+ }
+ });
+ });
+
+ // Cleanup
+ useEffect(() => {
+ return () => {
+ mediaRecorder.current?.stream.getTracks().forEach((t) => t.stop());
+ mediaRecorder.current?.stop();
+ timer.stop();
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ return {
+ start,
+ stop,
+ pauseResume,
+ allowed,
+ recordingBlob,
+ recordingStatus,
+ recordingTime: timer.time,
+ mediaRecorder,
+ };
+}
diff --git a/frontend/src/hooks/useTimer.ts b/frontend/src/hooks/useTimer.ts
new file mode 100644
index 0000000000..3f05c0c174
--- /dev/null
+++ b/frontend/src/hooks/useTimer.ts
@@ -0,0 +1,48 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+
+import { useState, useEffect, useRef } from "react";
+import useEvent from "react-use-event-hook";
+
+/**
+ * Creates a timer that counts returns the time in seconds.
+ * Interval is 100ms.
+ */
+export function useTimer() {
+ const [time, setTime] = useState(0);
+ const interval = useRef<number>();
+
+ const start = useEvent(() => {
+ interval.current = window.setInterval(() => {
+ setTime((time) => time + 0.1);
+ }, 100);
+ });
+
+ const stop = useEvent(() => {
+ if (interval.current != null) {
+ window.clearInterval(interval.current);
+ interval.current = undefined;
+ }
+ });
+
+ const clear = useEvent(() => {
+ setTime(0);
+ });
+
+ // Clear on unmount
+ useEffect(() => {
+ return () => {
+ window.clearInterval(interval.current);
+ };
+ }, []);
+
+ return {
+ // one decimal place, exactly
+ time: new Intl.NumberFormat("en-US", {
+ minimumFractionDigits: 1,
+ maximumFractionDigits: 1,
+ }).format(time),
+ start,
+ stop,
+ clear,
+ };
+}
diff --git a/frontend/src/plugins/impl/MicrophonePlugin.tsx b/frontend/src/plugins/impl/MicrophonePlugin.tsx
new file mode 100644
index 0000000000..3a78ee4bed
--- /dev/null
+++ b/frontend/src/plugins/impl/MicrophonePlugin.tsx
@@ -0,0 +1,57 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { z } from "zod";
+
+import { IPlugin, IPluginProps } from "@/plugins/types";
+import { Labeled } from "./common/labeled";
+import { useAudioRecorder } from "@/hooks/useAudioRecorder";
+import { AudioRecorder } from "@/components/audio/audio-recorder";
+import { blobToBase64 } from "@/utils/fileToBase64";
+
+/**
+ * Base64 encoded audio file.
+ */
+type Value = string;
+
+interface Data {
+ label?: string | null;
+}
+
+export class MicrophonePlugin implements IPlugin<Value, Data> {
+ tagName = "marimo-microphone";
+
+ validator = z.object({
+ label: z.string().nullish(),
+ });
+
+ render(props: IPluginProps<Value, Data>): JSX.Element {
+ return <Microphone {...props} />;
+ }
+}
+
+const Microphone = ({ setValue, data }: IPluginProps<Value, Data>) => {
+ const { start, stop, pauseResume, recordingStatus, recordingTime, allowed } =
+ useAudioRecorder({
+ onDone: async (file) => {
+ const [, base64] = await blobToBase64(file);
+ setValue(base64);
+ },
+ });
+
+ return (
+ <Labeled label={data.label} align="top">
+ {!allowed && (
+ <div className="text-destructive text-sm">
+ Microphone access is disabled. Please allow microphone access in your
+ browser.
+ </div>
+ )}
+ <AudioRecorder
+ onStart={start}
+ onStop={stop}
+ onPause={pauseResume}
+ status={recordingStatus}
+ time={recordingTime}
+ />
+ </Labeled>
+ );
+};
diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts
index 1c48780f0f..4a2e49c8e6 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -25,6 +25,7 @@ import { JsonOutputPlugin } from "./layout/JsonOutputPlugin";
import { TabsPlugin } from "./layout/TabsPlugin";
import { TexPlugin } from "./layout/TexPlugin";
import { RefreshPlugin } from "./impl/RefreshPlugin";
+import { MicrophonePlugin } from "./impl/MicrophonePlugin";
// List of UI plugins
const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
@@ -36,6 +37,7 @@ const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
new DropdownPlugin(),
new FileUploadPlugin(),
new FormPlugin(),
+ new MicrophonePlugin(),
new MultiselectPlugin(),
new NumberPlugin(),
new RadioPlugin(),
diff --git a/frontend/src/utils/fileToBase64.ts b/frontend/src/utils/fileToBase64.ts
index 93b0a0fc65..10b9affe26 100644
--- a/frontend/src/utils/fileToBase64.ts
+++ b/frontend/src/utils/fileToBase64.ts
@@ -1,5 +1,5 @@
/* Copyright 2023 Marimo. All rights reserved. */
-function fileToBase64(file: File): Promise<[string, string]> {
+export function blobToBase64(file: Blob): Promise<[string, string]> {
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(file);
@@ -20,5 +20,5 @@ function fileToBase64(file: File): Promise<[string, string]> {
* Returns a promised array of tuples [file name, file contents].
*/
export function filesToBase64(files: File[]): Promise<Array<[string, string]>> {
- return Promise.all(files.map((file) => fileToBase64(file)));
+ return Promise.all(files.map((file) => blobToBase64(file)));
}
diff --git a/marimo/__init__.py b/marimo/__init__.py
index abc123eff4..cd8f06f814 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -17,6 +17,7 @@ __all__ = [
"MarimoStopError",
"accordion",
"as_html",
+ "audio",
"callout",
"config",
"defs",
@@ -42,6 +43,7 @@ from marimo._output.hypertext import Html
from marimo._output.md import md
from marimo._plugins import ui
from marimo._plugins.stateless.accordion import accordion
+from marimo._plugins.stateless.audio import audio
from marimo._plugins.stateless.callout_output import callout
from marimo._plugins.stateless.flex import hstack, vstack
from marimo._plugins.stateless.image import image
diff --git a/marimo/_output/builder.py b/marimo/_output/builder.py
index 06d54ef381..045ed5c911 100644
--- a/marimo/_output/builder.py
+++ b/marimo/_output/builder.py
@@ -41,9 +41,25 @@ class _HTMLBuilder:
else:
return f"<img {_join_params(params)} />"
+ @staticmethod
+ def audio(
+ src: Optional[str] = None,
+ controls: bool = True,
+ ) -> str:
+ params: List[Tuple[str, str]] = []
+ if src:
+ params.append(("src", src))
+ if controls:
+ params.append(("controls", ""))
+
+ if len(params) == 0:
+ return "<audio />"
+ else:
+ return f"<audio {_join_params(params)} />"
+
def _join_params(params: List[Tuple[str, str]]) -> str:
- return " ".join([f"{k}='{v}'" for k, v in params])
+ return " ".join([f"{k}='{v}'" if v != "" else f"{k}" for k, v in params])
h = _HTMLBuilder()
diff --git a/marimo/_output/test_builder.py b/marimo/_output/test_builder.py
index 62f42a63d2..8e7a4d1b18 100644
--- a/marimo/_output/test_builder.py
+++ b/marimo/_output/test_builder.py
@@ -16,6 +16,13 @@ def test_img() -> None:
)
+def test_audio() -> None:
+ assert h.audio() == "<audio controls />"
+ assert (
+ h.audio(src="audio.mp3", controls=False) == "<audio src='audio.mp3' />"
+ )
+
+
def test_join_params() -> None:
assert (
_join_params([("style", "color:red"), ("class", "myClass")])
diff --git a/marimo/_plugins/stateless/audio.py b/marimo/_plugins/stateless/audio.py
new file mode 100644
index 0000000000..6df0c28a17
--- /dev/null
+++ b/marimo/_plugins/stateless/audio.py
@@ -0,0 +1,76 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+import base64
+import io
+from typing import Union
+
+from marimo._output.builder import h
+from marimo._output.hypertext import Html
+from marimo._output.rich_help import mddoc
+
+
+@mddoc
+def audio(
+ src: Union[str, io.IOBase],
+) -> Html:
+ """Render an audio file as HTML.
+
+ **Example.**
+
+ ```python3
+ mo.audio(
+ src="https://upload.wikimedia.org/wikipedia/commons/8/8c/Ivan_Ili%C4%87-Chopin_-_Prelude_no._1_in_C_major.ogg"
+ )
+
+ with open("recording.wav", "rb") as file:
+ mo.audio(src=file)
+ ```
+
+ **Args.**
+
+ - `src`: the URL of the audio or a file-like object
+
+ **Returns.**
+
+ An audio player as an `Html` object.
+ """
+ resolved_src = src if isinstance(src, str) else _io_to_data_url(src)
+ audio = h.audio(src=resolved_src, controls=True)
+ return Html(audio)
+
+
+def _io_to_data_url(readable: io.IOBase) -> str:
+ base64_string = base64.b64encode(readable.read()).decode("utf-8")
+ file_type = _guess_mime_type(readable)
+ return f"data:{file_type};base64,{base64_string}"
+
+
+def _guess_mime_type(src: Union[str, io.IOBase]) -> str:
+ file_name: str
+ if isinstance(src, str):
+ file_name = src
+ elif isinstance(src, io.FileIO):
+ src_name = src.name
+ if isinstance(src_name, str):
+ file_name = src_name
+ else:
+ # If we can't guess the file type, default to audio/wav
+ return "audio/wav"
+ else:
+ return "audio/wav"
+
+ file_type = file_name.split(".")[-1]
+ if file_type in INCONSISTENT_AUDIO_MIME_TYPES:
+ return f"audio/{INCONSISTENT_AUDIO_MIME_TYPES[file_type]}"
+ return f"audio/{file_type}"
+
+
+# Reference here:
+# https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
+INCONSISTENT_AUDIO_MIME_TYPES = {
+ "mp3": "mpeg",
+ "oga": "ogg",
+ "mid": "midi",
+ "weba": "webm",
+}
diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.py
index f51b95d4b0..b627848150 100644
--- a/marimo/_plugins/ui/__init__.py
+++ b/marimo/_plugins/ui/__init__.py
@@ -14,6 +14,7 @@ __all__ = [
"dropdown",
"file",
"form",
+ "microphone",
"multiselect",
"number",
"radio",
@@ -44,5 +45,6 @@ from marimo._plugins.ui._impl.input import (
text,
text_area,
)
+from marimo._plugins.ui._impl.microphone import microphone
from marimo._plugins.ui._impl.refresh import refresh
from marimo._plugins.ui._impl.switch import switch
diff --git a/marimo/_plugins/ui/_impl/microphone.py b/marimo/_plugins/ui/_impl/microphone.py
new file mode 100644
index 0000000000..36903dc084
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/microphone.py
@@ -0,0 +1,54 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+import base64
+import io
+from typing import Final
+
+from marimo._output.rich_help import mddoc
+from marimo._plugins.ui._core.ui_element import UIElement
+
+
+@mddoc
+class microphone(UIElement[str, io.BytesIO]):
+ """An audio recorder element.
+
+ Use `mo.microphone` to record audio via the user's browser. The
+ user must grant permission to use the microphone.
+
+ **Example.**
+
+ ```python
+ mic = mo.ui.microphone()
+ mic
+ ```
+
+ ```python
+ mo.audio(mic.value)
+ ```
+
+ **Attributes.**
+
+ - `value`: The blob of the recorded audio, as an `io.BytesIO` object.
+
+ **Initialization Args.**
+
+ - `label`: optional text label for the element
+ """
+
+ name: Final[str] = "marimo-microphone"
+
+ def __init__(
+ self,
+ *,
+ label: str = "",
+ ) -> None:
+ super().__init__(
+ component_name=microphone.name,
+ initial_value="",
+ label=label,
+ args={},
+ )
+
+ def _convert_value(self, value: str) -> io.BytesIO:
+ return io.BytesIO(base64.b64decode(value))
diff --git a/marimo/_smoke_tests/audio.py b/marimo/_smoke_tests/audio.py
new file mode 100644
index 0000000000..32b8eacd61
--- /dev/null
+++ b/marimo/_smoke_tests/audio.py
@@ -0,0 +1,34 @@
+# Copyright 2023 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.1.4"
+app = marimo.App()
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+def __(mo):
+ mic = mo.ui.microphone(label="What is your name?")
+ mic
+ return mic,
+
+
+def __(mic, mo):
+ mo.audio(mic.value)
+ return
+
+
+def __(mo):
+ mo.audio(src="https://samplelib.com/lib/preview/mp3/sample-3s.mp3")
+ return
+
+
+if __name__ == "__main__":
+ app.run()