Flutter PCM Sound 是一個 Flutter 套件,可將原始的 16 位整數 PCM 音訊資料即時播放至裝置喇叭。它提供底層音訊輸出,非常適合需要精確定時與極低延遲的應用程式,例如音訊合成、即時訊號處理或自訂音訊串流。此套件支援 Android、iOS 與 macOS,適用於跨平台音訊專案。它提供簡單的 API 來傳送音訊緩衝區,讓開發者能完全控制取樣率與格式來管理音訊串流。基於原生音訊 API 建構,確保跨平台的高效能表現。
適用情境
即時音訊合成
即時音訊信號處理
自定音訊串流
低延遲音頻播放
音頻可視化
主要特色
支援16位整數PCM
即時音頻輸出
跨平台(Android、iOS、macOS)
低延遲音頻傳輸
簡單的基於緩衝區的 API
適合對象
音頻開發者
即時訊號處理
遊戲音頻引擎
需要細緻控制的音樂應用程式
嵌入式音訊系統
使用建議
需要手動管理音訊緩衝區
無內建音訊檔案解碼
僅限 PCM 格式
可能需要特定於平台的音訊設定
不適用於一般用途的音頻播放
原始 README
以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。
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.
Set a large feed threshold so that flutter_pcm_sound regularly tells you its remainingFrames
Start a Dart-side Timer.periodic(...) or Ticker
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';
typedefFeedCallback = List<int> Function(int remainingFrames);
/// wraps FlutterPcmSound w/ timer-based feedingclassFlutterPcmTimer{
// --- config ---staticint _sampleRate = 48000;
staticint _channelCount = 1;
staticint _tickHz = 60;
// --- state ---staticFeedCallback? _onFeed;
staticbool _isSetup = false;
staticbool _playing = false;
staticTimer? _timer;
// last native event snapshotstaticint _lastEventFrames = 0;
staticint _lastEventMicros = 0; // timestamp// for UIstaticboolget isPlaying => _playing;
staticFuture<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;
awaitFlutterPcmSound.setup(
sampleRate: _sampleRate,
channelCount: _channelCount,
iosAudioCategory: iosAudioCategory,
iosAllowBackgroundAudio: iosAllowBackgroundAudio,
);
// Huge threshold → plugin regularly reports `remainingFrames`.awaitFlutterPcmSound.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;
}
staticvoidsetFeedCallback(FeedCallback? cb) => _onFeed = cb;
staticvoidstart() {
if (!_isSetup) throwStateError('Call SoundTimer.setup(...) first.');
if (_playing) return;
_playing = true;
FlutterPcmSound.start();
final period = Duration(milliseconds: (1000 / _tickHz).round());
_timer ??= Timer.periodic(period, (_) => _tick());
}
staticvoidstop() {
if (!_playing && _timer == null) return;
_playing = false;
_timer?.cancel();
_timer = null;
}
// --- internals ---staticvoid_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 asyncawaitFlutterPcmSound.feed(PcmArrayInt16.fromList(samples));
}
staticint_estimatedRemainingFramesNow() {
final lastFrames = _lastEventFrames;
final lastMicros = _lastEventMicros;
if (lastMicros == 0) return0;
final elapsedMicros = _nowMicros() - lastMicros;
final elapsedFrames = ((elapsedMicros / 1e6) * _sampleRate).round();
final est = lastFrames - elapsedFrames;
return est > 0 ? est : 0;
}
staticint_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 platformvoidonFeed(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);
awaitFlutterPcmSound.feed(PcmArrayInt16.fromList(frame));
}
awaitFlutterPcmSound.setup(sampleRate: 44100, channelCount: 1);
awaitFlutterPcmSound.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