Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Tone.Js Playback #27

Merged
merged 3 commits into from
Jan 3, 2025
Merged

Added Tone.Js Playback #27

merged 3 commits into from
Jan 3, 2025

Conversation

leouofa
Copy link
Owner

@leouofa leouofa commented Jan 3, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added audio synthesis functionality to the notes page
    • Introduced interactive note playback with click interactions
    • Implemented synthesizer selection mechanism
  • Dependencies

    • Added Tone.js library for audio synthesis
    • Restructured project dependencies
  • Performance

    • Optimized audio sample loading with singleton pattern
    • Enhanced user interaction with responsive note elements

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
Copy link

vercel bot commented Jan 3, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
gridbeat ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 3, 2025 2:16am

Copy link

coderabbitai bot commented Jan 3, 2025

Walkthrough

This pull request introduces audio synthesis capabilities to the application by integrating Tone.js into the notes and grid components. The changes focus on adding interactive audio playback functionality, allowing users to play musical notes through a graphical interface. A new singleton class manages piano sample loading, and the components are updated to support different synthesizer types and provide a more engaging musical experience.

Changes

File Change Summary
app/notes/page.tsx - Added synth state variable for audio synthesis
- Implemented playNote function for note playback
- Updated note elements with click handlers and interaction styles
components/Grid.tsx - Added PianoSamplerSingleton class for managing piano samples
- Updated GridProps to support synthesizer type selection
- Introduced instrument and isLoading state variables
- Enhanced note playback functionality
package.json - Removed next dependency
- Added tone dependency
- Restructured various dependencies

Sequence Diagram

Loading
sequenceDiagram
    participant User
    participant NotesPage
    participant Synthesizer
    participant AudioContext

    User->>NotesPage: Click on note
    NotesPage->>AudioContext: Start audio context
    AudioContext-->>NotesPage: Context ready
    NotesPage->>Synthesizer: Play note
    Synthesizer-->>User: Produce sound

Possibly related PRs

Poem

🎵 A rabbit's melody takes flight,
With Tone.js, notes now shine bright
Clicks bring music to the screen
A symphony of code, serene
Synthesizing joy, pure delight! 🐰🎹


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
app/notes/page.tsx (1)

22-31: playNote function
Handling octave formatting and starting the audio context is a neat solution. Consider a way to configure the note duration if needed.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b7f7f21 and 8a213ac.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • app/notes/page.tsx (4 hunks)
  • components/Grid.tsx (2 hunks)
  • package.json (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
components/Grid.tsx

[error] 9-38: Avoid classes that contain only static members.

Prefer using simple functions instead of classes with only static members.

(lint/complexity/noStaticOnlyClass)


[error] 16-16: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 16-16: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 17-17: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 18-18: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 28-28: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 29-29: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 35-35: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 36-36: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 90-90: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

🔇 Additional comments (21)
components/Grid.tsx (11)

3-3: Imported React, useState, useEffect
This import looks fine and aligns well with the usage below.


8-8: Tone.js import is correct
Bringing in Tone.js via import * as Tone is consistent with usage throughout this file.


40-40: SynthType enum-like type
Defining this union type is straightforward and clear.


45-45: Optional synthType in GridProps
This approach is flexible. The default prop value is handled elsewhere, ensuring no runtime issues.


52-52: Default synthType assignment
Destructuring synthType = "poly" clarifies the default. Good use of TypeScript optional.

Also applies to: 53-57


59-63: Instrument and loading states
Storing the current instrument and loading state is well-structured, making the UI more responsive.


111-111: Spacing or blank line
No issue here; the blank line adds clarity.


112-115: Preloading piano
Eager loading of the piano sampler can improve user experience. This is a good usage pattern.


117-145: playNote logic
The approach to compute note/octave is creative. Confirm if the infinite octave increments are desirable or if you might cap at a certain octave. Keep an eye on performance for large iterations.


147-149: Conditional loading message
Displaying a loading message is user-friendly.


270-270: Grid cell styling and click handler
Adding hover and active states in combination with onClick is effective for interactive UI.

Also applies to: 276-276

app/notes/page.tsx (7)

1-1: "use client" directive
This ensures proper client-side rendering.


5-5: Tone.js import
Consistently importing Tone.js aligns with usage.


9-10: Synth state
Good approach to manage the synth instance in React state.


11-20: useEffect for synth initialization
Creating and disposing the synth on mount/unmount is correct.


54-55: Clickable note elements
Good addition of cursor and hover styles for improved UX.


71-71: Styling each note
Dynamically styling based on color/textColor is well-handled.

Also applies to: 76-76


98-98: Sharps/flats styling
Providing a distinct style for sharps highlights note categories effectively.

Also applies to: 103-103

package.json (3)

12-12: Legacy Next.js reference
Still present at line 12. Check if it’s intentionally kept or should be fully removed since your environment may not rely on it.


15-15: tone dependency
Adding "tone": "^15.0.4" is essential for the new playback features.


18-18: Re-adding devDependencies
Confirm that the re-addition is correct. No version changes appear, so it might be a housekeeping reorganization.

Also applies to: 24-25, 26-26

Comment on lines +64 to +110
useEffect(() => {
let newInstrument: typeof instrument = null;
let mounted = true;

const setupInstrument = async () => {
setIsLoading(true);

switch (synthType) {
case "piano":
newInstrument = await PianoSamplerSingleton.getInstance();
break;

case "poly":
newInstrument = new Tone.PolySynth(Tone.Synth, {
oscillator: {
type: "triangle",
},
envelope: {
attack: 0.02,
decay: 0.1,
sustain: 0.3,
release: 1,
},
}).toDestination();
break;

case "basic":
default:
newInstrument = new Tone.Synth().toDestination();
break;
}

if (mounted) {
setInstrument(newInstrument);
setIsLoading(false);
}
};

setupInstrument();

return () => {
mounted = false;
if (newInstrument && synthType !== "piano") {
newInstrument.dispose();
}
};
}, [synthType]);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Instrument setup and cleanup
The logic for initializing different instruments and disposing them when unmounted is solid. Consider removing the redundant “case ‘basic’:” if you always fall back to default in the switch statement.

      switch (synthType) {
        case "piano":
          ...
          break;
        case "poly":
          ...
          break;
-       case "basic":
-       default:
+       default:
          newInstrument = new Tone.Synth().toDestination();
          break;
      }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
let newInstrument: typeof instrument = null;
let mounted = true;
const setupInstrument = async () => {
setIsLoading(true);
switch (synthType) {
case "piano":
newInstrument = await PianoSamplerSingleton.getInstance();
break;
case "poly":
newInstrument = new Tone.PolySynth(Tone.Synth, {
oscillator: {
type: "triangle",
},
envelope: {
attack: 0.02,
decay: 0.1,
sustain: 0.3,
release: 1,
},
}).toDestination();
break;
case "basic":
default:
newInstrument = new Tone.Synth().toDestination();
break;
}
if (mounted) {
setInstrument(newInstrument);
setIsLoading(false);
}
};
setupInstrument();
return () => {
mounted = false;
if (newInstrument && synthType !== "piano") {
newInstrument.dispose();
}
};
}, [synthType]);
useEffect(() => {
let newInstrument: typeof instrument = null;
let mounted = true;
const setupInstrument = async () => {
setIsLoading(true);
switch (synthType) {
case "piano":
newInstrument = await PianoSamplerSingleton.getInstance();
break;
case "poly":
newInstrument = new Tone.PolySynth(Tone.Synth, {
oscillator: {
type: "triangle",
},
envelope: {
attack: 0.02,
decay: 0.1,
sustain: 0.3,
release: 1,
},
}).toDestination();
break;
default:
newInstrument = new Tone.Synth().toDestination();
break;
}
if (mounted) {
setInstrument(newInstrument);
setIsLoading(false);
}
};
setupInstrument();
return () => {
mounted = false;
if (newInstrument && synthType !== "piano") {
newInstrument.dispose();
}
};
}, [synthType]);
🧰 Tools
🪛 Biome (1.9.4)

[error] 90-90: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

Comment on lines +10 to +38
class PianoSamplerSingleton {
private static instance: Tone.Sampler | null = null;
private static isLoading = false;
private static loadPromise: Promise<void> | null = null;

static async getInstance(): Promise<Tone.Sampler> {
if (!this.instance && !this.loadPromise) {
this.isLoading = true;
this.loadPromise = new Promise((resolve) => {
const sampler = new Tone.Sampler({
urls: {
C4: "C4.mp3",
"D#4": "Ds4.mp3",
"F#4": "Fs4.mp3",
A4: "A4.mp3",
},
baseUrl: "https://tonejs.github.io/audio/salamander/",
onload: () => {
this.instance = sampler;
this.isLoading = false;
resolve();
},
}).toDestination();
});
}
await this.loadPromise;
return this.instance!;
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor static-only class to simpler structure
A class with only static members adds overhead and is flagged by static analysis. Consider refactoring to a simple module-level function or object. Also, replace this references with the class name for clarity in static methods.

-class PianoSamplerSingleton {
-  private static instance: Tone.Sampler | null = null;
-  ...
-}
+let pianoSampler: Tone.Sampler | null = null;
+let isSamplerLoading = false;
+let loadPromise: Promise<void> | null = null;
+
+export async function getPianoSamplerInstance(): Promise<Tone.Sampler> {
+  if (!pianoSampler && !loadPromise) {
+    isSamplerLoading = true;
+    loadPromise = new Promise((resolve) => {
+      const sampler = new Tone.Sampler({ ... }).toDestination();
+      ...
+    });
+  }
+  await loadPromise;
+  return pianoSampler!;
+}

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Biome (1.9.4)

[error] 9-38: Avoid classes that contain only static members.

Prefer using simple functions instead of classes with only static members.

(lint/complexity/noStaticOnlyClass)


[error] 16-16: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 16-16: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 17-17: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 18-18: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 28-28: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 29-29: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 35-35: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 36-36: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

@leouofa leouofa merged commit ea6cf4b into main Jan 3, 2025
3 checks passed
@leouofa leouofa deleted the add-tonejs branch January 3, 2025 02:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant