패키지, 저장소 및 앱 카테고리 검색

패키지 상세v3.3.3

flutter_pcm_sound

실시간 PCM 오디오(16비트 정수)를 기기 스피커로 전송합니다

AndroidiOSmacOS
30일 다운로드
3.9만
좋아요
45
Pub 점수
140

패키지 설치

flutter pub add flutter_pcm_sound

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Flutter PCM Sound는 디바이스 스피커에 직접 실시간으로 16비트 정수 PCM 오디오 데이터를 재생할 수 있는 Flutter 패키지입니다. 정밀한 타이밍과 최소 지연을 필요로 하는 애플리케이션(예: 오디오 합성, 라이브 신호 처리, 사용자 정의 오디오 스트리밍)에 적합한 저수준 오디오 출력을 제공합니다. Android, iOS, macOS를 지원하여 크로스플랫폼 오디오 프로젝트에 적합합니다. 샘플레이트와 포맷에 대한 완전한 제어가 가능한 간단한 API를 통해 오디오 버퍼를 전송할 수 있습니다. 네이티브 오디오 API 기반으로 구현되어 모든 플랫폼에서 효율적인 성능을 보장합니다.

사용 사례

  • 실시간 오디오 합성
  • 라이브 오디오 신호 처리
  • 사용자 정의 오디오 스트리밍
  • 저지연 오디오 재생
  • 오디오 시각화

주요 기능

  • 16비트 정수 PCM 지원
  • 실시간 오디오 출력
  • 크로스 플랫폼(안드로이드, iOS, macOS)
  • 저지연 오디오 전달
  • 간단한 버퍼 기반 API

적합한 대상

  • 오디오 개발자
  • 실시간 신호 처리
  • 게임 오디오 엔진
  • 정교한 제어가 필요한 음악 앱
  • 임베디드 오디오 시스템

고려 사항

  • 음성 버퍼를 수동으로 관리해야 합니다
  • 내장된 오디오 파일 디코딩 없음
  • PCM 형식으로만 제한
  • 플랫폼별 오디오 구성이 필요할 수 있습니다
  • 일반적인 오디오 재생을 위한 것이 아님

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

pub package

Logo

Send real-time PCM audio (16-bit integer) to your device speakers, from your Flutter app!

No Dependencies

FlutterPcmSound has zero dependencies besides Flutter, Android, iOS, and MacOS themselves.

For Real-Time Audio, Not Audio Files

Unlike other plugins, flutter_pcm_sound does not use audio files (For example: flutter_soloud, sound_pool).

Instead, flutter_pcm_sound is for apps that generate audio in realtime a few milliseconds before you hear it. For example, using dart_melty_soundfont.

Callback Based

In contrast to raw_sound, FlutterPcmSound uses a callback setFeedCallback to signal when to feed more samples.

You can lower the feed threshold using setFeedThreshold to achieve real time audio, or increase it to have a cushy buffer.

Event Based Feeding

Unlike traditional audio libraries which use a high-frequency timer-based audio callback, flutter_pcm_sound uses a low-frequency event-based callback. This integrates more seamlessly in the existing Flutter event loop, without necessitating an Isolate to ensure precise timing.

Your feed callback is invoked once for each of these events:

  • Low-buffer event – when the number of buffered frames falls below the threshold set with setFeedThreshold, i.e remainingFrames < threshold.
  • Zero event – when the buffer is fully drained, i.e. remainingFrames == 0.

Note: once means once per feed() — every time you feed new data, the plugin will trigger another low-buffer or zero event when necessary.

💡 Tip: By altering how many extra samples you feed beyond your threshold, you can control how often flutter_pcm_sound invokes your feed callback.

💡 Tip: You should still consider running your sound code in a Dart Isolate, so that it is decoupled from UI framedrops.

Timer Based Feeding

If you prefer, it's easy to wrap flutter_pcm_sound to simulate traditional timer-based feeding, i.e. invoking your feed callback at a specific preferrred rate, using a Dart timer.

  1. Set a large feed threshold so that flutter_pcm_sound regularly tells you its remainingFrames

  2. Start a Dart-side Timer.periodic(...) or Ticker

  3. On each timer tick, call your feed callback with the estimated remaining frames. i.e. estimatedRemainingFrames = remainingFrames - (elapsedSeconds * sampleRate)

For an example, click here
import 'dart:async';
import 'package:flutter_pcm_sound/flutter_pcm_sound.dart';

typedef FeedCallback = List<int> Function(int remainingFrames);

/// wraps FlutterPcmSound w/ timer-based feeding
class FlutterPcmTimer {
  // --- config ---
  static int _sampleRate = 48000;
  static int _channelCount = 1;
  static int _tickHz = 60;

  // --- state ---
  static FeedCallback? _onFeed;
  static bool _isSetup = false;
  static bool _playing = false;
  static Timer? _timer;

  // last native event snapshot
  static int _lastEventFrames = 0;
  static int _lastEventMicros = 0; // timestamp

  // for UI
  static bool get isPlaying => _playing;

  static Future<void> setup({
    int sampleRate = 48000,
    int channelCount = 1,
    int tickHz = 60,
    IosAudioCategory iosAudioCategory = IosAudioCategory.playback,
    bool iosAllowBackgroundAudio = false,
  }) async {
    _sampleRate = sampleRate;
    _channelCount = channelCount;
    _tickHz = tickHz;

    await FlutterPcmSound.setup(
      sampleRate: _sampleRate,
      channelCount: _channelCount,
      iosAudioCategory: iosAudioCategory,
      iosAllowBackgroundAudio: iosAllowBackgroundAudio,
    );

    // Huge threshold → plugin regularly reports `remainingFrames`.
    await FlutterPcmSound.setFeedThreshold(_sampleRate * 60 * 60 * 24 * 365);

    FlutterPcmSound.setFeedCallback((remaining) {
      _lastEventFrames = remaining;
      _lastEventMicros = _nowMicros();
      if (remaining == 0 && _playing) {
        // Refill ASAP, but outside the native callback.
        scheduleMicrotask(_tick);
      }
    });

    _isSetup = true;
  }
  
  static void setFeedCallback(FeedCallback? cb) => _onFeed = cb;

  static void start() {
    if (!_isSetup) throw StateError('Call SoundTimer.setup(...) first.');
    if (_playing) return;

    _playing = true;
    FlutterPcmSound.start();

    final period = Duration(milliseconds: (1000 / _tickHz).round());
    _timer ??= Timer.periodic(period, (_) => _tick());
  }

  static void stop() {
    if (!_playing && _timer == null) return;
    _playing = false;
    _timer?.cancel();
    _timer = null;
  }

  // --- internals ---

  static void _tick() async {
    if (!_playing) return;

    final estRemaining = _estimatedRemainingFramesNow();
    if (_onFeed == null) return;

    final samples = _onFeed!(estRemaining);
    if (samples.isEmpty) return;

    if (!_playing) return; // guard before async
    await FlutterPcmSound.feed(PcmArrayInt16.fromList(samples));
  }

  static int _estimatedRemainingFramesNow() {
    final lastFrames = _lastEventFrames;
    final lastMicros = _lastEventMicros;
    if (lastMicros == 0) return 0;

    final elapsedMicros = _nowMicros() - lastMicros;
    final elapsedFrames = ((elapsedMicros / 1e6) * _sampleRate).round();
    final est = lastFrames - elapsedFrames;
    return est > 0 ? est : 0;
  }

  static int _nowMicros() => DateTime.now().microsecondsSinceEpoch;
}

One-Pedal Driving

To play audio, just keep calling feed.

To stop audio, just stop calling feed.

💡 Tip: If you prefer a traditional timer-based API with start() and stop(), I recommend wrapping flutter_pcm_sound as described in Timer Based Feeding.

Is Playing?

When your feed callback hits remainingFrames=0 you know playing stopped.

Usage

// for testing purposes, a C-Major scale 
MajorScale scale = MajorScale(sampleRate: 44100, noteDuration: 0.25);

// invoked whenever we need to feed more samples to the platform
void onFeed(int remainingFrames) async {
    // you could use 'remainingFrames' to feed very precisely.
    // But here we just load a few thousand samples everytime we run low.
    List<int> frame = scale.generate(periods: 20);
    await FlutterPcmSound.feed(PcmArrayInt16.fromList(frame));
}

await FlutterPcmSound.setup(sampleRate: 44100, channelCount: 1);
await FlutterPcmSound.setFeedThreshold(8000); 
FlutterPcmSound.setFeedCallback(onFeed);
FlutterPcmSound.start(); // for convenience. Equivalent to calling onFeed(0);

⭐ Stars ⭐

Please star this repo & on pub.dev. We all benefit from having a larger community.

Example App

Enable the platforms you need.

cd ./example                      
flutter config --enable-macos-desktop                                                      
flutter config --enable-android 
flutter config --enable-ios 
flutter create .
flutter run

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트