### Start Audio Playback with PlayerStream.start() Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Starts the audio player, enabling it to play queued audio chunks. This should be called after initialization and before writing any audio data using `writeChunk()`. ```dart import 'dart:typed_data'; import 'package:sound_stream/sound_stream.dart'; final player = PlayerStream(); await player.initialize(); await player.start(); // Player is now ready to receive and play audio chunks ``` -------------------------------- ### PlayerStream.start() Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Starts the audio player, making it ready to receive and play audio chunks. This should be called after initialization and before writing any audio data. ```APIDOC ## PlayerStream.start() ### Description Starts the audio player and begins playing any queued audio chunks. After calling `start()`, use `writeChunk()` to feed audio data to the player. ### Method `start()` ### Endpoint N/A (Method call) ### Parameters None ### Request Example ```dart import 'dart:typed_data'; import 'package:sound_stream/sound_stream.dart'; final player = PlayerStream(); await player.initialize(); await player.start(); // Player is now ready to receive and play audio chunks ``` ### Response #### Success Response (void) This method does not return a value upon successful start. #### Error Response Throws an exception if the player is not initialized or if starting fails. ``` -------------------------------- ### Record and Play Audio in Flutter Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt This Dart code snippet demonstrates a complete example of recording audio from the microphone, storing it in memory, and then playing it back using the sound_stream package. It handles initialization, starting/stopping recording and playback, and listening to status changes. ```dart import 'dart:async'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:sound_stream/sound_stream.dart'; class AudioRecorderPlayer extends StatefulWidget { @override _AudioRecorderPlayerState createState() => _AudioRecorderPlayerState(); } class _AudioRecorderPlayerState extends State { final RecorderStream _recorder = RecorderStream(); final PlayerStream _player = PlayerStream(); List _recordedChunks = []; bool _isRecording = false; bool _isPlaying = false; StreamSubscription? _recorderStatus; StreamSubscription? _playerStatus; StreamSubscription? _audioStream; @override void initState() { super.initState(); _initAudio(); } Future _initAudio() async { // Listen for recorder status changes _recorderStatus = _recorder.status.listen((status) { setState(() { _isRecording = status == SoundStreamStatus.Playing; }); }); // Listen for player status changes _playerStatus = _player.status.listen((status) { setState(() { _isPlaying = status == SoundStreamStatus.Playing; }); }); // Collect audio chunks during recording _audioStream = _recorder.audioStream.listen((Uint8List data) { _recordedChunks.add(data); }); // Initialize both recorder and player await Future.wait([ _recorder.initialize(sampleRate: 16000), _player.initialize(sampleRate: 16000), ]); } Future _startRecording() async { _recordedChunks.clear(); await _recorder.start(); } Future _stopRecording() async { await _recorder.stop(); } Future _playRecording() async { if (_recordedChunks.isEmpty) return; await _player.start(); // Play all recorded chunks for (var chunk in _recordedChunks) { await _player.writeChunk(chunk); } } Future _stopPlayback() async { await _player.stop(); } @override void dispose() { _recorderStatus?.cancel(); _playerStatus?.cancel(); _audioStream?.cancel(); _recorder.dispose(); _player.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( children: [ IconButton( icon: Icon(_isRecording ? Icons.stop : Icons.mic), onPressed: _isRecording ? _stopRecording : _startRecording, ), IconButton( icon: Icon(_isPlaying ? Icons.pause : Icons.play_arrow), onPressed: _isPlaying ? _stopPlayback : _playRecording, ), Text('Chunks recorded: ${_recordedChunks.length}'), ], ); } } ``` -------------------------------- ### Initialize Audio Recorder with Sample Rate Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Initializes the microphone recorder, setting the audio sample rate. This method must be called before starting any recording operations. It supports custom sample rates and optional debug logging. ```dart import 'package:sound_stream/sound_stream.dart'; final recorder = RecorderStream(); // Initialize with default 16kHz sample rate await recorder.initialize(); // Or with custom sample rate and logging await recorder.initialize( sampleRate: 44100, // CD quality showLogs: true, // Enable debug logging ); ``` -------------------------------- ### Start Audio Recording and Stream Data Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Begins capturing audio from the microphone. Captured audio data is streamed as `Uint8List` chunks containing PCM 16-bit data. Recording continues until `stop()` is invoked. Ensure `initialize()` is called first and subscribe to `audioStream`. ```dart import 'dart:typed_data'; import 'package:sound_stream/sound_stream.dart'; final recorder = RecorderStream(); List audioChunks = []; // Initialize first await recorder.initialize(); // Subscribe to audio stream before starting recorder.audioStream.listen((Uint8List chunk) { audioChunks.add(chunk); print('Received ${chunk.length} bytes of audio data'); }); // Start recording await recorder.start(); // ... recording in progress ... // Stop recording after some time await recorder.stop(); print('Total chunks recorded: ${audioChunks.length}'); ``` -------------------------------- ### Subscribe to Real-time Audio Data Stream Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Subscribes to the `audioStream` of the `RecorderStream` to receive `Uint8List` chunks of PCM 16-bit audio data in real-time. This stream is essential for processing audio data as it's captured, for example, sending it over a network or performing analysis. ```dart import 'dart:async'; import 'dart:typed_data'; import 'package:sound_stream/sound_stream.dart'; final recorder = RecorderStream(); StreamSubscription? subscription; await recorder.initialize(); // Subscribe to audio stream subscription = recorder.audioStream.listen((Uint8List data) { // Process audio data (send over network, save, analyze, etc.) print('Audio chunk: ${data.length} bytes'); }); await recorder.start(); // Later, clean up subscription?.cancel(); ``` -------------------------------- ### Stop Audio Recording Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Stops the ongoing audio recording process. This action ceases the transmission of audio data chunks to the `audioStream`. The recorder can be re-initialized and started again after being stopped. ```dart import 'package:sound_stream/sound_stream.dart'; final recorder = RecorderStream(); await recorder.initialize(); await recorder.start(); // Record for 5 seconds await Future.delayed(Duration(seconds: 5)); // Stop recording await recorder.stop(); ``` -------------------------------- ### Register Service Worker for Flutter Sound Stream Source: https://github.com/casperpas/flutter-sound-stream/blob/master/example/web/index.html This snippet shows how to register a service worker for the Flutter Sound Stream application. It checks for service worker support in the browser and registers 'flutter_service_worker.js' upon successful page load. This is typically used for background audio processing or offline capabilities. ```javascript if ('serviceWorker' in navigator) { window.addEventListener('load', function () { navigator.serviceWorker.register('flutter_service_worker.js'); }); } ``` -------------------------------- ### Access SoundStream Singleton Instances Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Demonstrates how to access the singleton instances of SoundStream, RecorderStream, and PlayerStream. These instances manage platform channel communication and provide access to audio streaming functionalities. ```dart import 'package:sound_stream/sound_stream.dart'; // Access the singleton instances final soundStream = SoundStream(); final recorder = soundStream.recorder; // RecorderStream instance final player = soundStream.player; // PlayerStream instance // Or access directly (also returns singletons) final recorderDirect = RecorderStream(); final playerDirect = PlayerStream(); ``` -------------------------------- ### Initialize Audio Player with PlayerStream.initialize() Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Initializes the audio player with a specified sample rate. This method must be called before any playback operations. It can accept a custom sample rate and an option to enable logging. ```dart import 'package:sound_stream/sound_stream.dart'; final player = PlayerStream(); // Initialize with default 16kHz sample rate await player.initialize(); // Or with custom sample rate await player.initialize( sampleRate: 44100, showLogs: true, ); ``` -------------------------------- ### PlayerStream.initialize() Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Initializes the audio player. This method must be called before any other player operations. You can specify a custom sample rate and enable logging. ```APIDOC ## PlayerStream.initialize() ### Description Initializes the audio player with the specified sample rate. The sample rate must match the audio data being played. Must be called before starting playback. ### Method `initialize()` ### Parameters #### Query Parameters - **sampleRate** (int) - Optional - The sample rate for audio playback (e.g., 16000, 44100). Defaults to 16000. - **showLogs** (bool) - Optional - If true, enables verbose logging for the player. ### Request Example ```dart import 'package:sound_stream/sound_stream.dart'; final player = PlayerStream(); // Initialize with default 16kHz sample rate await player.initialize(); // Or with custom sample rate and logging enabled await player.initialize( sampleRate: 44100, showLogs: true, ); ``` ### Response #### Success Response (void) This method does not return a value upon successful initialization. #### Error Response Throws an exception if initialization fails (e.g., due to invalid sample rate or platform issues). ``` -------------------------------- ### WebSocket Audio Streaming for Voice Chat in Flutter Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt This Dart code demonstrates how to implement real-time audio streaming over WebSockets using the sound_stream and web_socket_channel packages. It allows a client to send recorded audio to a server and receive audio from other clients for voice communication. ```dart import 'dart:async'; import 'package:sound_stream/sound_stream.dart'; import 'package:web_socket_channel/io.dart'; class VoiceChatClient { final RecorderStream _recorder = RecorderStream(); final PlayerStream _player = PlayerStream(); late IOWebSocketChannel _channel; StreamSubscription? _audioSubscription; bool _isConnected = false; Future connect(String serverUrl) async { // Connect to WebSocket server _channel = IOWebSocketChannel.connect(serverUrl); _isConnected = true; // Initialize audio components await Future.wait([ _recorder.initialize(sampleRate: 16000), _player.initialize(sampleRate: 16000), ]); // Receive audio from other clients and play _channel.stream.listen((data) { if (_isConnected) { _player.writeChunk(data); } }); // Send recorded audio to server _audioSubscription = _recorder.audioStream.listen((data) { if (_isConnected) { _channel.sink.add(data); } }); // Start player to receive incoming audio await _player.start(); } Future startTalking() async { await _recorder.start(); } Future stopTalking() async { await _recorder.stop(); } Future disconnect() async { _isConnected = false; await _audioSubscription?.cancel(); await _recorder.stop(); await _player.stop(); await _channel.sink.close(); } } // Usage void main() async { final client = VoiceChatClient(); await client.connect('wss://your-server.com/audio'); // Push-to-talk pattern await client.startTalking(); await Future.delayed(Duration(seconds: 5)); await client.stopTalking(); await client.disconnect(); } ``` -------------------------------- ### PlayerStream.writeChunk() Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Pushes a chunk of PCM 16-bit audio data to the player's buffer for playback. Chunks are played in the order they are received. ```APIDOC ## PlayerStream.writeChunk() ### Description Pushes PCM 16-bit audio data to the player's buffer for playback. Chunks are queued and played sequentially in the order they are received. ### Method `writeChunk(Uint8List chunk)` ### Parameters #### Path Parameters - **chunk** (Uint8List) - Required - A byte buffer containing PCM 16-bit audio data. ### Request Example ```dart import 'dart:typed_data'; import 'package:sound_stream/sound_stream.dart'; final player = PlayerStream(); final recorder = RecorderStream(); await player.initialize(); await recorder.initialize(); // Start player first await player.start(); // Play recorded chunks List recordedChunks = []; // Previously recorded audio for (var chunk in recordedChunks) { await player.writeChunk(chunk); } // Or stream directly from recorder to player (real-time passthrough) recorder.audioStream.listen((Uint8List data) { player.writeChunk(data); }); await recorder.start(); ``` ### Response #### Success Response (void) This method does not return a value upon successfully queuing the audio chunk. #### Error Response Throws an exception if the player is not initialized or started, or if the data format is incorrect. ``` -------------------------------- ### Dart WebSocket Server for Audio Broadcasting Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt A simple WebSocket server written in Dart that broadcasts audio data between connected clients. It manages a set of active WebSocket connections and relays incoming audio chunks to all other connected clients, excluding the sender. This is useful for multi-party voice communication applications. ```dart import 'dart:io' show HttpServer, HttpRequest, WebSocket, WebSocketTransformer; const int PORT = 8888; void main() { final connections = Set(); HttpServer.bind('localhost', PORT).then((HttpServer server) { print('[+] WebSocket listening at ws://localhost:$PORT/'); server.listen((HttpRequest request) { WebSocketTransformer.upgrade(request).then((WebSocket ws) { connections.add(ws); print('[+] Client connected. Total: ${connections.length}'); ws.listen( (data) { // Broadcast audio data to all other connected clients for (var conn in connections) { if (conn != ws && conn.readyState == WebSocket.open) { conn.add(data); } } }, onDone: () { connections.remove(ws); print('[-] Client disconnected. Total: ${connections.length}'); }, onError: (err) { connections.remove(ws); print('[!] Error: ${err.toString()}'); }, cancelOnError: true, ); }); }); }); } // Run with: dart server.dart ``` -------------------------------- ### Write Audio Data with PlayerStream.writeChunk() Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Pushes PCM 16-bit audio data to the player's buffer for playback. Audio chunks are processed sequentially. This method is crucial for feeding audio data to the player, either from recorded sources or real-time streams. ```dart import 'dart:typed_data'; import 'package:sound_stream/sound_stream.dart'; final player = PlayerStream(); final recorder = RecorderStream(); await player.initialize(); await recorder.initialize(); // Start player first await player.start(); // Play recorded chunks List recordedChunks = []; // Previously recorded audio for (var chunk in recordedChunks) { await player.writeChunk(chunk); } // Or stream directly from recorder to player (real-time passthrough) recorder.audioStream.listen((Uint8List data) { player.writeChunk(data); }); await recorder.start(); ``` -------------------------------- ### PlayerStream.usePhoneSpeaker() Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Controls the audio output device, forcing playback through the phone's main speaker or switching back to the earpiece/headset. ```APIDOC ## PlayerStream.usePhoneSpeaker() ### Description Forces audio output to use the phone's built-in speaker instead of earpiece or connected headset. Useful for speakerphone mode in communication apps. ### Method `usePhoneSpeaker(bool useSpeaker)` ### Parameters #### Path Parameters - **useSpeaker** (bool) - Required - Set to `true` to use the phone speaker, `false` to use the default output (earpiece/headset). ### Request Example ```dart import 'package:sound_stream/sound_stream.dart'; final player = PlayerStream(); await player.initialize(); await player.start(); // Switch to phone speaker await player.usePhoneSpeaker(true); // Switch back to earpiece/headset await player.usePhoneSpeaker(false); ``` ### Response #### Success Response (void) This method does not return a value upon successful switching of the audio output. #### Error Response Throws an exception if the operation fails on the specific platform. ``` -------------------------------- ### Monitor Player Status with PlayerStream.status Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Provides a stream of `SoundStreamStatus` values, allowing observation of the player's current state. This is useful for updating UI or triggering actions based on playback status changes. ```dart import 'package:sound_stream/sound_stream.dart'; final player = PlayerStream(); player.status.listen((SoundStreamStatus status) { switch (status) { case SoundStreamStatus.Unset: print('Player not initialized'); break; case SoundStreamStatus.Initialized: print('Player ready'); break; case SoundStreamStatus.Playing: print('Playback active'); break; case SoundStreamStatus.Stopped: print('Playback stopped'); break; } }); ``` -------------------------------- ### PlayerStream.status Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Provides a stream of `SoundStreamStatus` values, allowing you to monitor the current state of the audio player (e.g., Initialized, Playing, Stopped). ```APIDOC ## PlayerStream.status ### Description A stream that emits `SoundStreamStatus` values indicating the current state of the player. ### Method `status` (Stream) ### Endpoint N/A (Property access) ### Parameters None ### Request Example ```dart import 'package:sound_stream/sound_stream.dart'; final player = PlayerStream(); player.status.listen((SoundStreamStatus status) { switch (status) { case SoundStreamStatus.Unset: print('Player not initialized'); break; case SoundStreamStatus.Initialized: print('Player ready'); break; case SoundStreamStatus.Playing: print('Playback active'); break; case SoundStreamStatus.Stopped: print('Playback stopped'); break; } }); ``` ### Response #### Success Response (Stream) - **status** (SoundStreamStatus) - The current status of the audio player. Possible values include `Unset`, `Initialized`, `Playing`, `Stopped`. #### Error Response The stream may complete with an error if there's an unrecoverable issue with the audio player. ``` -------------------------------- ### Monitor Recorder Status Stream Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Listens to the `status` stream of the `RecorderStream` to monitor the current state of the audio recorder. This is useful for updating the user interface based on the recorder's status, such as 'Initialized', 'Playing', or 'Stopped'. ```dart import 'package:sound_stream/sound_stream.dart'; final recorder = RecorderStream(); // Listen for status changes recorder.status.listen((SoundStreamStatus status) { switch (status) { case SoundStreamStatus.Unset: print('Recorder not initialized'); break; case SoundStreamStatus.Initialized: print('Recorder ready'); break; case SoundStreamStatus.Playing: print('Recording in progress'); break; case SoundStreamStatus.Stopped: print('Recording stopped'); break; } }); await recorder.initialize(); await recorder.start(); // Status: Playing await recorder.stop(); // Status: Stopped ``` -------------------------------- ### Switch Audio Output with PlayerStream.usePhoneSpeaker() Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Forces audio output to use the phone's built-in speaker. This is useful for enabling speakerphone functionality in communication applications. It can be toggled on or off. ```dart import 'package:sound_stream/sound_stream.dart'; final player = PlayerStream(); await player.initialize(); await player.start(); // Switch to phone speaker await player.usePhoneSpeaker(true); // Switch back to earpiece/headset await player.usePhoneSpeaker(false); ``` -------------------------------- ### PlayerStream.stop() Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Stops the audio player. Any audio data currently buffered or playing may be discarded. ```APIDOC ## PlayerStream.stop() ### Description Stops the audio player. Any remaining audio in the buffer may be discarded. ### Method `stop()` ### Endpoint N/A (Method call) ### Parameters None ### Request Example ```dart import 'package:sound_stream/sound_stream.dart'; final player = PlayerStream(); await player.initialize(); await player.start(); // ... playing audio ... await player.stop(); ``` ### Response #### Success Response (void) This method does not return a value upon successful stop. #### Error Response Throws an exception if the player is not in a state where it can be stopped. ``` -------------------------------- ### Stop Audio Playback with PlayerStream.stop() Source: https://context7.com/casperpas/flutter-sound-stream/llms.txt Stops the audio player, ceasing any current playback. Audio data remaining in the buffer may be discarded upon stopping. ```dart import 'package:sound_stream/sound_stream.dart'; final player = PlayerStream(); await player.initialize(); await player.start(); // ... playing audio ... await player.stop(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.