DartMeltySoundFont - a SoundFont synthesizer (i.e. '.sf2' player) written in pure Dart

Overview

DartMeltySoundFont

DartMeltySoundFont is a SoundFont synthesizer (i.e. '.sf2' player) written in pure Dart.

It is a port of MeltySynth (C#, MIT License) written by Nobuaki Tanaka, to Dart.

https://github.com/sinshu/meltysynth

Dependencies

This package has no dependencies.

Maintanence

Apart from breaking changes to the Dart language (rare), this package has no external dependencies and should work on any Dart SDK >=2.12 indefinitely. This package was written against Dart SDK 2.16.1.

Example

Ssynthesize a simple chord:


// Necessary Imports
import 'package:dart_melty_soundfont/dart_melty_soundfont.dart';
import 'package:flutter/services.dart' show rootBundle;

// Create the synthesizer.
ByteData bytes = await rootBundle.load('assets/akai_steinway.sf2');

Synthesizer synth = Synthesizer.loadByteData(bytes, 
    SynthesizerSettings(
        sampleRate: 44100, 
        blockSize: 64, 
        maximumPolyphony: 64, 
        enableReverbAndChorus: true,
    ));

// Turn on some notes
synth.noteOn(channel: 0, key: 72, velocity: 120);
synth.noteOn(channel: 0, key: 76, velocity: 120);
synth.noteOn(channel: 0, key: 79, velocity: 120);
synth.noteOn(channel: 0, key: 82, velocity: 127);

// Render the waveform (3 seconds)
ArrayInt16 buf16 = ArrayInt16.zeros(numShorts: 44100 * 3);

synth.renderMonoInt16(buf16);

Features

  • No memory allocation in the rendering process.

  • Wave synthesis

    • SoundFont reader
    • Waveform generator
    • Envelope generator
    • Low-pass filter
    • Vibrato LFO
    • Modulation LFO
  • MIDI message processing

    • Note on/off
    • Bank selection
    • Modulation
    • Volume control
    • Pan
    • Expression
    • Hold pedal
    • Program change
    • Pitch bend
    • Tuning
  • Effects

    • Reverb
    • Chorus
  • Other things

    • Loop extension support
    • Performace optimization

Todo

  • MIDI file support.

Feel free to port MIDI file support to Dart and make a pull request.

Its usage would look like this when implemented:

// Create the synthesizer.
var sampleRate = 44100;
var synthesizer = new Synthesizer("TimGM6mb.sf2", sampleRate);

// Read the MIDI file.
var midiFile = MidiFile("flourish.mid");
var sequencer = MidiFileSequencer(synthesizer);
sequencer.play(midiFile, false);

// Render the waveform (3 seconds)
ArrayInt16 buf16 = ArrayInt16.zeros(numShorts: 44100 * 3);

sequencer.renderMonoInt16(buf16);

License

DartMeltySoundFont is available under the MIT license.

References

Comments
  • SampleEndLoop error comes up

    SampleEndLoop error comes up

    I am getting a flutter: 'sampleEndLoop' is out of range. 'STRING error. My code

    static byteToPlayer() async { try{ // Create the synthesizer. ByteData bytes = await rootBundle.load(defaultURL);

      Synthesizer synth = Synthesizer.loadByteData(bytes);
    
      // Turn on some notes
      synth.noteOn(channel: 0, key: noteToPlay, velocity: 120);
    
      // Render the waveform (3 seconds)
      ArrayInt16 buf16 = ArrayInt16.zeros(numShorts: 44100 * 3);
    
      synth.renderMonoInt16(buf16);
    
      return {"bytes" : buf16.bytes.buffer.asUint8List(), "isSuccessful": true};
    }catch(e){
      print('byteToPlayer');
      print(e);
      return {"bytes" : 0, "isSuccessful": false};
    }
    

    }

    opened by nathanblanchard12 16
  • metronom.sf renders all zeros

    metronom.sf renders all zeros

    How can I play the rendered ArrayInt16 in a player like flutter_sounds?

    I've tried the following but it doesn't work:

        // Render the waveform (3 seconds)
        final buf16 = ArrayInt16.zeros(numShorts: sampleRate * 3);
        synth.renderMonoInt16(buf16);
    
        // play
        final bytes = buf16.bytes.buffer.asUint8List();
        player.startPlayer(
          fromDataBuffer: bytes,
          codec: Codec.pcm16,
          whenFinished: () => debugPrint("Calibrator.play – finished."),
        );
    

    DO zou have an example for how to play the ArrayInt16?

    opened by abegehr 11
  • Render function fails with exception

    Render function fails with exception

    Thanks for this great port of MeltySynth which I use in my C# project.

    I'm trying to create a Flutter version of my project but the library has a weird problem which does not exist in the C# version.

    Here's the sample application which demonstrates the problem:

    DartMeltySoundFontTest.zip

    My real application feeds the sound output with synthesized midi data.

    The sample application simulates this with the following loop:

    image

    However after a few seconds, an exception occurs in the following function:

    image

    If I encapsulate this part in a try/catch block everything seems to work fine but I'm not sure if it has any side effects or creates performance problems.

    Can you please check what's wrong here?

    opened by postacik 6
  • Import as Package

    Import as Package

    Thank you for building and publishing this package! I'm unable to import any resources from the package after install in in pubspec.yaml. The example references a non-package import: https://pub.dev/packages/dart_melty_soundfont#example I'm looking for a package import like referenced here: https://dart.dev/guides/libraries/create-library-packages#importing-library-files

    opened by abegehr 5
  • modify to be a valid package

    modify to be a valid package

    Please merge this and update version numbering. The src directory is moved into lib directory, and modify lib/src/synthesizer.dart not to use flutter package (to keep it pure dart). If there are multiple necessary imports, you can export them from single file.

    opened by marrlex 4
  • Build Failure on iOS with Readme example code

    Build Failure on iOS with Readme example code

    I'm running the example code from the readme: https://pub.dev/packages/dart_melty_soundfont#example And am getting a build failure on iOS.

    Build failure logs
    ** BUILD FAILED **
    Xcode's output:
    ↳
        Writing result bundle at path:
        	[/var/folders/qm/p7v8v0tn1rs_7lzhx8s_39q00000gn/T/flutter_tools.EXfodr/flutter_ios_build_temp_dirqI0dsC/temporary_xcresult_bundle]()
    : Error: Type 'ByteData' not found.
    ../…/lib/synthesizer.dart:112
            factory Synthesizer.loadByteData(ByteData data, [SynthesizerSettings? settings])
                                             ^^^^^^^^
    : Error: Expected ';' after this.
    ../…/services/binding.dart:374
              ui.channelBuffers.setListenerchannel, (ByteData? data, ui.PlatformMessageResponseCallback callback) async {
                                ^^^^^^^^^^^^^^^^^^
    : Error: Expected an identifier, but got ','.
    ../…/services/binding.dart:374
        Try inserting an identifier before ','.
              ui.channelBuffers.setListenerchannel, (ByteData? data, ui.PlatformMessageResponseCallback callback) async {
                                                  ^
    : Error: Unexpected token ','.
    ../…/services/binding.dart:374
              ui.channelBuffers.setListenerchannel, (ByteData? data, ui.PlatformMessageResponseCallback callback) async {
                                                  ^
    : Error: Expected ';' after this.
    ../…/services/binding.dart:388
              });
              ^
    : Error: Expected an identifier, but got ')'.
    ../…/services/binding.dart:388
        Try inserting an identifier before ')'.
              });
               ^
    : Error: Unexpected token ')'.
    ../…/services/binding.dart:388
              });
               ^
    : Error: The getter 'setListenerchannel' isn't defined for the class 'ChannelBuffers'.
    ../…/services/binding.dart:374
         - 'ChannelBuffers' is from 'dart:ui'.
        Try correcting the name to the name of an existing getter, or defining a getter or field named 'setListenerchannel'.
              ui.channelBuffers.setListenerchannel, (ByteData? data, ui.PlatformMessageResponseCallback callback) async {
                                ^^^^^^^^^^^^^^^^^^
    : Error: 'ByteData' isn't a type.
    ../…/lib/synthesizer.dart:112
            factory Synthesizer.loadByteData(ByteData data, [SynthesizerSettings? settings])
                                             ^^^^^^^^
        Failed to package [/Users/anton/local/repos/mashup.]()
        Command PhaseScriptExecution failed with a nonzero exit code
        note: Using new build system
        note: Planning
        note: Build preparation complete
        note: Building targets in dependency order
        Result bundle written to path:
        	[/var/folders/qm/p7v8v0tn1rs_7lzhx8s_39q00000gn/T/flutter_tools.EXfodr/flutter_ios_build_temp_dirqI0dsC/temporary_xcresult_bundle]()
    Could not build the precompiled application for the device.
    
    Flutter doctor output
    [flutter] flutter doctor -v
    [✓] Flutter (Channel beta, 2.11.0-0.1.pre, on macOS 12.3 21E5222a darwin-x64, locale en-DE)
        • Flutter version 2.11.0-0.1.pre at /Users/anton/development/flutter
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision b101bfe32f (2 weeks ago), 2022-02-16 07:36:54 -0800
        • Engine revision e355993572
        • Dart version 2.17.0 (build 2.17.0-69.2.beta)
        • DevTools version 2.10.0-dev.1
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
        • Android SDK at /Users/anton/Library/Android/sdk
        • Platform android-32, build-tools 32.0.0
        • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7281165)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 13.3)
        • Xcode at /Applications/Xcode-beta.app/Contents/Developer
        • CocoaPods version 1.11.2
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2020.3)
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7281165)
    
    [✓] VS Code (version 1.62.3)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.29.0
    
    [✓] Connected device (2 available)
        • Anton’s iPhone (mobile) • 00008101-0002249636B8001E • ios            • iOS 15.4 19E5241a
        • Chrome (web)            • chrome                    • web-javascript • Google Chrome 99.0.4844.51
    
    [✓] HTTP Host Availability
        • All required HTTP hosts are available
    
    • No issues found!
    exit code 0
    
    
    opened by abegehr 3
  • A bug due to a typo

    A bug due to a typo

    A bug due to a typo was found in the C# version. It seems that the Dart version also has this bug. Please check this issue: https://github.com/sinshu/meltysynth/issues/15

    https://github.com/chipweinberger/DartMeltySoundFont/blob/914b72fbe09fe8e6918bf4c37ca4968ecc2db6aa/lib/synthesizer.dart#L217-L223

    opened by sinshu 2
  • Exception occurs for some sound font files

    Exception occurs for some sound font files

    meltysynth library raises an exception for some sound font files.

    It was fixed in the last commit.

    Can you please apply the same fix to your library?

    https://github.com/sinshu/meltysynth/issues/14#issuecomment-1114255892

    opened by postacik 2
  • Example project For Web

    Example project For Web

    Hello can you add an example to the project. It would be easier to figure out if it works. I might be using it wrong but I hear no audio. I am not sure if it is my sf2 file or computer or settings

    opened by nathanblanchard12 1
  • How to connect to raw_sound?

    How to connect to raw_sound?

    Can you please help me how to connect DartMeltySoundFont with raw_sound?

    I am using this example from raw_sound: https://pub.dev/packages/raw_sound/example

    In that example, there is this line

    await _playerPCMI16.feed(dataBlock);
    

    Which apparently "Feeds the player with raw PCM [data] block" according to the documentation of this method. The parameter of feed() is expected to be of the type Uint8List.

    When I look at the sample code of DartMeltySoundFont, I see the variable buf16 of the type ArrayInt16.

    How do I cast ArrayInt16 to Uint8List?

    Thanks for your help. I am new to the area of digital sound creation.

    opened by lukassteiner 4
  • Midi file support

    Midi file support

    Hi, I added midi file sequencer feature in my fork.

    I tried to obey your style of conversion from C#.

    The code is not battle tested but it works with my test midi files as you can see in the video below:

    https://user-images.githubusercontent.com/3977227/167107533-c0a27b20-8b96-4be5-9d10-d0bec5dfa44a.mp4

    I hope it would help you to complete the library :)

    opened by postacik 3
Owner
Chip Weinberger
Chip Weinberger
Lightweight and blazing fast key-value database written in pure Dart.

Fast, Enjoyable & Secure NoSQL Database Hive is a lightweight and blazing fast key-value database written in pure Dart. Inspired by Bitcask. Documenta

HiveDB 3.4k Dec 30, 2022
Lightweight and blazing fast key-value database written in pure Dart.

Fast, Enjoyable & Secure NoSQL Database Hive is a lightweight and blazing fast key-value database written in pure Dart. Inspired by Bitcask. Documenta

HiveDB 3.4k Dec 30, 2022
A simple set of terminal-based arcade games written in pure Dart.

dartcade A simple set of terminal-based arcade games written in pure Dart. Purpose I was developing some simple 2D UI libraries (such as package:gridd

Matan Lurey 7 Dec 7, 2022
SurrealDB client written in pure dart. auto reconnect, typed functions

SurrealDB Client For Dart & Flutter SurrealDB client for Dart and Flutter. Quick Start import 'package:surrealdb/surrealdb.dart'; void main(List<Stri

Duhan BALCI 10 Dec 18, 2022
This is the Zuri Chat Android app project repository handled by TEAM SOCRATES, written with pure Flutter.

Zuri Chat Overview This is the Zuri Chat Android app project repository handled by TEAM SOCRATES, written with pure Flutter. NB: Always contact Team l

Zuri Chat 32 Nov 22, 2022
Tic Tac Toe game with single-player and multi-player options. Implemented minimax algorithm.

flutter_tic_tac_toe A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you star

null 0 Jan 1, 2022
Flutter-Musive-app - Full-stack music player app written in flutter and dart using node.js music API

Musive Full-stack music player app is written in flutter and dart using node.js

Ansh rathod 69 Dec 28, 2022
Pure Dart Client for Nakama Server 🌟🥰🤩

Nakama Flutter Client ?? ?? ?? ?? Nakama is an open-source scalable game server. This is a Flutter client for Nakama written in pure dart and supports

Oliver Brunsmann 57 Dec 6, 2022
A simple day / night switcher widget made in pure Dart.

DayNightSwitcher Just a simple simple day / night switcher widget made in pure Dart. It allows you to quickly show a beautiful dark mode switcher widg

Hugo Delaunay 38 Oct 28, 2022
Dart port of FormCoreJS: A minimal pure functional language based on self dependent types.

FormCore.js port to Dart. So far only the parser and typechecker have been ported i.e. the FormCore.js file in the original repo. (Original readme fro

Modestas Valauskas 2 Jan 28, 2022
Animated dialog box - A pure dart package for showing animated alert box.

animated_dialog_box A pure dart package for showing animated alert box. Getting Started https://github.com/Shubham-Narkhede/animated_dialog_box/blob/m

Shubham-Narkhede 10 Jul 24, 2022
A pure Dart utility library that checks for an internet connection by opening a socket to a list of specified addresses, each with individual port and timeout. Defaults are provided for convenience.

data_connection_checker A pure Dart utility library that checks for an internet connection by opening a socket to a list of specified addresses, each

Kristiyan Mitev 103 Nov 29, 2022
This project was writed with pure dart code,which means it's support both iOS and Android.

This project was writed with pure dart code,which means it's support both iOS and Android. Screenshot Todo show/hide animation Usage You can find the

吴述军 Brant 377 Dec 24, 2022
A pure Dart package for working with RDF (resource description framework).

RDFLib A pure Dart package for working with RDF (resource description framework). Features Create triple instances (with data types) Create a graph to

null 5 Dec 15, 2022
Mysql.dart - MySQL client for Dart written in Dart

Native MySQL client written in Dart for Dart See example directory for examples

null 48 Dec 29, 2022
Interview questions and answers for preparation, built in pure flutter also have CI implementation for learning.

toughest An app for interview preparation. Unique animations. More than 100 questions and answer. Good UI. Featured in many websites. For Vietnam user

Md Sadab Wasim 239 Dec 27, 2022
Pure: a Social Network Messenger app developed using Flutter

Pure Pure is a Social Network Messenger app developed using Flutter. Generated b

Aanu Olakunle 28 Oct 7, 2022
Petrus Nguyễn Thái Học 193 Dec 29, 2022
A flutter brain game built using only pure flutter animations.

Flutter Brain Game ?? ?? ?? This project designed using figma and built using flutter. Demo URL https://khalid-alsaleh-dev.github.io/BrainGame/#/ ?? R

Khalid Al-Saleh 6 Jun 17, 2022