Giter Site home page Giter Site logo

daniilalpha / minisound Goto Github PK

View Code? Open in Web Editor NEW
2.0 1.0 1.0 2.19 MB

A high-level real-time audio playback library for Flutter, based on miniaudio.

Kotlin 0.10% Dart 21.82% CMake 30.41% C++ 17.86% C 6.03% HTML 1.60% Ruby 1.72% JavaScript 0.99% Makefile 19.48%
audio audio-playback audio-playback-library dart dart-package dart3 flutter flutter-package miniaudio realtime-audio

minisound's Introduction

minisound

A high-level real-time audio playback library based on miniaudio. The library offers basic functionality and quite low latency. Not really suitable for big sounds right now. Supports MP3, WAV and FLAC formats.

Platform support

Platform Tested Supposed to work Unsupported
Android SDK 31, 19 SDK 16+ SDK 15-
iOS None Unknown Unknown
Windows 11, 7 (x64) Vista+ XP-
macOS None Unknown Unknown
Linux Fedora 39 Any None
Web Chrome 93+, Firefox 79+, Safari 16+ Browsers with an AudioWorklet support Browsers without an AudioWorklet support

Getting started on the web

While the main script is quite large, there are a loader script provided. Include it in the web/index.html file like this

  <script src="assets/packages/minisound_web/js/minisound_web.loader.js"></script>

It is highly recommended NOT to make the script defer, as loading may not work properly. Also, it is very small (only 18 lines).

And at the bottom, at the body's <script> do like this

window.addEventListener(
  'load',
  // ADD 'async'
  async function (ev) {
      // ADD THIS LINE AT THE TOP
      await _minisound.loader.load();

      // LEAVE THE REST IN PLACE
      // Download main.dart.js
      _flutter.loader.loadEntrypoint({
        serviceWorker: {
          serviceWorkerVersion: serviceWorkerVersion
        },
        onEntrypointLoaded: function (engineInitializer) {
          engineInitializer.initializeEngine().then(function (appRunner) {
            appRunner.runApp();
          });
        }
      });
    }
  );

Minisound uses SharedArrayBuffer feature, so you should enable cross-origin isolation on your site.

Usage

To use this plugin, add minisound as a dependency in your pubspec.yaml file.

import "package:minisound/minisound.dart" as minisound;

void main() {
  final engine = minisound.Engine();

  // this method takes an update period in milliseconds as an argument, which
  // determines the length of the latency (does not currently affect the web)
  await engine.init(); 

  // there is also a 'loadSound' method to load a sound from the Uint8List
  final sound = await engine.loadSoundAsset("asset/path.ext");
  sound.volume = 0.5;

  // this may cause a MinisoundPlatformException to be thrown on the web
  // before any user interaction due to the autoplay policy
  await engine.start(); 

  sound.play();

  await Future.delayed(sound.duration*.5);

  sound.pause(); // this method saves sound position
  sound.stop(); // but this does not

  sound.isLooped = true; // sound will now be looped
  sound.play();

  await Future.delayed(sound.duration*5);

  sound.stop();

  // it is recommended to unload sounds manually to prevent memory leaks
  sound.unload(); 

  // the engine and all loaded sounds will be automatically disposed when 
  // engine gets garbage-collected
}

minisound's People

Contributors

daniilalpha avatar

Stargazers

 avatar  avatar

Watchers

 avatar

minisound's Issues

Repeated playback error

When the music has not been played yet, clicking play again will cause an error.

Win10 x64
PS C:\Windows\system32> flutter --version
Flutter 3.10.2 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 9cd3d0d9ff (9 weeks ago) • 2023-05-23 20:57:28 -0700
Engine • revision 90fa3ae28f
Tools • Dart 3.0.2 • DevTools 2.23.1
PS C:\Windows\system32>

code

import 'package:flutter/material.dart';
import "package:minisound/minisound.dart" as minisound;

class Test2 extends StatefulWidget {
  const Test2({Key? key}) : super(key: key);

  @override
  _Test2State createState() => _Test2State();
}

class _Test2State extends State<Test2> {
  @override
  Widget build(BuildContext context) {
    final engine = minisound.Engine();

    return Scaffold(
      appBar: AppBar(
        title: const Text('Test Play'),
      ),
      body: ElevatedButton(
        child: const Text("play"),
        onPressed: () async {
          await engine.init();
          final sound = await engine
              .loadSoundFile("C:\\Users\\FangJun\\Music\\我会好好的 - 王心凌.mp3");
          await engine.start();
          sound.play();
        },
      ),
    );
  }
}

error:

Flutter assets will be downloaded from https://mirrors.tuna.tsinghua.edu.cn/flutter. Make sure you trust this source!
Launching lib\main.dart on Windows in debug mode...
√  Built build\windows\runner\Debug\fmusic.exe.
Connecting to VM Service at ws://127.0.0.1:10766/YcJzBaabtFU=/ws
DEBUG: Loading library: user32.dll
DEBUG: Loading symbol: GetForegroundWindow
DEBUG: Loading symbol: GetDesktopWindow
DEBUG: Loading library: advapi32.dll
DEBUG: Loading symbol: RegOpenKeyExA
DEBUG: Loading symbol: RegCloseKey
DEBUG: Loading symbol: RegQueryValueExA
DEBUG: Loading library: ole32.dll
DEBUG: Loading symbol: CoInitialize
DEBUG: Loading symbol: CoInitializeEx
DEBUG: Loading symbol: CoUninitialize
DEBUG: Loading symbol: CoCreateInstance
DEBUG: Loading symbol: CoTaskMemFree
DEBUG: Loading symbol: PropVariantClear
DEBUG: Loading symbol: StringFromGUID2
DEBUG: Attempting to initialize WASAPI backend...
DEBUG: Loading library: kernel32.dll
DEBUG: Loading symbol: VerifyVersionInfoW
DEBUG: Loading symbol: VerSetConditionMask
DEBUG: Loading library: avrt.dll
DEBUG: Loading symbol: AvSetMmThreadCharacteristicsA
DEBUG: Loading symbol: AvRevertMmThreadCharacteristics
DEBUG: System Architecture:
DEBUG:   Endian: LE
DEBUG:   SSE2:   YES
DEBUG:   AVX2:   YES
DEBUG:   NEON:   NO
DEBUG: [WASAPI] Trying IAudioClient3_InitializeSharedAudioStream(actualPeriodInFrames=441)
DEBUG:     defaultPeriodInFrames=441
DEBUG:     fundamentalPeriodInFrames=441
DEBUG:     minPeriodInFrames=441
DEBUG:     maxPeriodInFrames=441
DEBUG: [WASAPI] Using IAudioClient3
DEBUG:     periodSizeInFramesOut=441
INFO: [WASAPI]
INFO:   扬声器 (USB Audio Device) (Playback)
INFO:     Format:      32-bit IEEE Floating Point -> 32-bit IEEE Floating Point
INFO:     Channels:    2 -> 2
INFO:     Sample Rate: 44100 -> 44100
INFO:     Buffer Size: 441*3 (1323)
INFO:     Conversion:
INFO:       Pre Format Conversion:  NO
INFO:       Post Format Conversion: NO
INFO:       Channel Routing:        NO
INFO:       Resampling:             NO
INFO:       Passthrough:            YES
INFO:       Channel Map In:         {CHANNEL_FRONT_LEFT CHANNEL_FRONT_RIGHT}
INFO:       Channel Map Out:        {CHANNEL_FRONT_LEFT CHANNEL_FRONT_RIGHT}
[engine.c:63 info] engine initialized successfully!
[engine.c:109 info] sound loaded successfully!
[engine.c:83 info] engine started successfully
[engine.c:132 info] sound played successfully!
DEBUG: Loading library: user32.dll
DEBUG: Loading symbol: GetForegroundWindow
DEBUG: Loading symbol: GetDesktopWindow
DEBUG: Loading library: advapi32.dll
DEBUG: Loading symbol: RegOpenKeyExA
DEBUG: Loading symbol: RegCloseKey
DEBUG: Loading symbol: RegQueryValueExA
DEBUG: Loading library: ole32.dll
DEBUG: Loading symbol: CoInitialize
DEBUG: Loading symbol: CoInitializeEx
DEBUG: Loading symbol: CoUninitialize
DEBUG: Loading symbol: CoCreateInstance
DEBUG: Loading symbol: CoTaskMemFree
DEBUG: Loading symbol: PropVariantClear
DEBUG: Loading symbol: StringFromGUID2
DEBUG: Attempting to initialize WASAPI backend...
DEBUG: Loading library: kernel32.dll
DEBUG: Loading symbol: VerifyVersionInfoW
DEBUG: Loading symbol: VerSetConditionMask
DEBUG: Loading library: avrt.dll
DEBUG: Loading symbol: AvSetMmThreadCharacteristicsA
DEBUG: Loading symbol: AvRevertMmThreadCharacteristics
DEBUG: System Architecture:
DEBUG:   Endian: LE
DEBUG:   SSE2:   YES
DEBUG:   AVX2:   YES
DEBUG:   NEON:   NO
DEBUG: [WASAPI] Trying IAudioClient3_InitializeSharedAudioStream(actualPeriodInFrames=441)
DEBUG:     defaultPeriodInFrames=441
DEBUG:     fundamentalPeriodInFrames=441
DEBUG:     minPeriodInFrames=441
DEBUG:     maxPeriodInFrames=441
DEBUG: [WASAPI] Using IAudioClient3
DEBUG:     periodSizeInFramesOut=441
INFO: [WASAPI]
INFO:   扬声器 (USB Audio Device) (Playback)
INFO:     Format:      32-bit IEEE Floating Point -> 32-bit IEEE Floating Point
INFO:     Channels:    2 -> 2
INFO:     Sample Rate: 44100 -> 44100
INFO:     Buffer Size: 441*3 (1323)
INFO:     Conversion:
INFO:       Pre Format Conversion:  NO
INFO:       Post Format Conversion: NO
INFO:       Channel Routing:        NO
INFO:       Resampling:             NO
INFO:       Passthrough:            YES
INFO:       Channel Map In:         {CHANNEL_FRONT_LEFT CHANNEL_FRONT_RIGHT}
INFO:       Channel Map Out:        {CHANNEL_FRONT_LEFT CHANNEL_FRONT_RIGHT}
Lost connection to device.
[engine.c:63 i
Exited (sigterm)

111

Will it work on Macos too?

I ran it on mac os and got this error.

2023-08-02 11:10:43.762 xcodebuild[27539:261165] DVTCoreDeviceEnabledState: DVTCoreDeviceEnabledState_Disabled set via user default (DVTEnableCoreDevice=disabled) /Users/ijungho/.pub-cache/hosted/pub.dev/minisound_ffi-1.1.0/macos/Classes/minisound_ffi.c:3:10: fatal error: '../../src/minisound_ffi.c' file not found #include "../../src/minisound_ffi.c" ^~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 error generated.

loadSound supposed to work ?

Hello!

Having trouble to try this function. When loading a Uint8List of data the app crashes. Any clue ?

INFO:   Built-in Audio Digital Stereo (HDMI) (Playback)
INFO:     Format:      32-bit IEEE Floating Point -> 32-bit IEEE Floating Point
INFO:     Channels:    2 -> 2
INFO:     Sample Rate: 48000 -> 48000
INFO:     Buffer Size: 1440*1 (1440)
INFO:     Conversion:
INFO:       Pre Format Conversion:  NO
INFO:       Post Format Conversion: 
Lost connection to device.
Failed to send request: {"jsonrpc":"2.0","id":"20","method":"getObject","params":{"isolateId":"isolates/3140592888150543","objectId":"libraries/@557171358"}}

is not working on IOS

It's work well on Android,
but i got this error 'Lexical or Preprocessor Issue (Xcode): '../../src/external/milo/src/milo.c' file not found
/Users/patrickImusic/.pub-cache/hosted/pub.dev/minisound_ffi-1.3.8/ios/Classes/minisound_ffi.c:6:9'
when i'm trying to run on IOS

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.