Skip to content

Commit

Permalink
feat: generate uid where one hasn't been provided
Browse files Browse the repository at this point in the history
generate a uid where one hasn't been provided. this will help update the state when a new playback is started
  • Loading branch information
lukeocodes committed May 5, 2024
1 parent 6aa03d1 commit ca63929
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
17 changes: 6 additions & 11 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import React from "react";
import { silence } from "./lib/contants";
import { randomId } from "./lib/utils";

/**
* React context for managing audio playback, including playing, stopping, and resuming audio tracks.
Expand All @@ -23,9 +24,9 @@ interface NowPlayingContext extends Partial<Omit<HTMLAudioElement, "play">> {
play: (audio: MediaSource | Blob | string, type?: string, uid?: string) => Promise<void>;

/**
* Pauses audio playback at the current position.
*/
pause: () => void;
* Pauses audio playback at the current position.
*/
pause?: () => void;

/**
* Resumes audio playback from the current position.
Expand Down Expand Up @@ -91,7 +92,7 @@ const NowPlayingContextProvider = ({ children }: NowPlayingContextInterface) =>
uid?: string
): Promise<void> => {
if (!player || !source) return;
if (uid) setUid(uid);
uid ? setUid(uid) : setUid(randomId(7));

let url = audio as string;

Expand All @@ -110,12 +111,6 @@ const NowPlayingContextProvider = ({ children }: NowPlayingContextInterface) =>
return player.play();
};

const pause = () => {
if (!player) return;

player.pause();
};

const stop = () => {
if (!player) return;

Expand All @@ -135,7 +130,7 @@ const NowPlayingContextProvider = ({ children }: NowPlayingContextInterface) =>
value={{
player,
play,
pause,
pause: player?.pause,
resume,
stop,
uid,
Expand Down
12 changes: 12 additions & 0 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Generate random string of alphanumerical characters.
*
* @param {number} length this is the length of the string to return
* @returns {string}
*/
export function randomId(length: number): string {
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
return Array.from({ length }, () =>
characters.charAt(Math.floor(Math.random() * characters.length))
).join("");
}

1 comment on commit ca63929

@vercel
Copy link

@vercel vercel bot commented on ca63929 May 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.