如何在Flutter中播放网络音频?在线电台App插件故障求助
Hey there! I’ve built a couple of Flutter radio apps before, so I totally get the frustration when plugins don’t cooperate. Let’s go through a tried-and-true approach using stable packages that should get your online radio up and running smoothly.
Step 1: Add Dependencies
Start by adding these well-maintained packages to your pubspec.yaml — they handle most edge cases for audio playback and system integration:
dependencies: flutter: sdk: flutter just_audio: ^0.9.34 # Core audio playback handler audio_session: ^0.1.14 # Manages audio focus and background behavior permission_handler: ^10.2.0 # Handles platform permission prompts
Run flutter pub get to install them fully.
Step 2: Configure Platform Permissions
Android
Open android/app/src/main/AndroidManifest.xml and add these permissions inside the <manifest> tag:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA" /> <!-- Required for Android 12+ -->
iOS
Open ios/Runner/Info.plist and add these entries inside the <dict> tag:
<!-- Skip if your radio uses HTTPS; allows HTTP streams --> <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> <!-- Enables background audio playback --> <key>UIBackgroundModes</key> <array> <string>audio</string> </array> <!-- Permission prompt description --> <key>NSForegroundUsageDescription</key> <string>Playing online radio in the background</string>
Step 3: Core Playback Logic
Create a reusable service class to handle radio playback — this keeps your code organized:
import 'package:audio_session/audio_session.dart'; import 'package:just_audio/just_audio.dart'; class RadioPlayer { final AudioPlayer _audioPlayer = AudioPlayer(); bool _isPlaying = false; String? _radioStreamUrl; bool get isPlaying => _isPlaying; Future<void> init(String streamUrl) async { _radioStreamUrl = streamUrl; // Set up audio session to respect system rules (e.g., pause on calls) final session = await AudioSession.instance; await session.configure(const AudioSessionConfiguration.speech()); // Listen for playback state changes _audioPlayer.playbackEventStream.listen((event) { _isPlaying = event.processingState == ProcessingState.ready && !event.isStopped; }); } Future<void> togglePlayPause() async { if (_radioStreamUrl == null) return; try { if (_isPlaying) { await _audioPlayer.pause(); } else { await _audioPlayer.setUrl(_radioStreamUrl!); await _audioPlayer.play(); } } catch (e) { print("Playback error: $e"); } } Future<void> dispose() async { await _audioPlayer.dispose(); } }
Key Details:
AudioSessionensures your app plays nicely with other audio apps (like pausing when a phone call starts).just_audiosupports most streaming protocols (HLS, MP3, AAC) — just confirm your radio URL is a valid direct stream first.
Step 4: Build a Basic UI
Here’s how to integrate the player into a simple screen:
import 'package:flutter/material.dart'; class RadioScreen extends StatefulWidget { const RadioScreen({super.key}); @override State<RadioScreen> createState() => _RadioScreenState(); } class _RadioScreenState extends State<RadioScreen> { final RadioPlayer _radioPlayer = RadioPlayer(); final String _myRadioUrl = "https://your-radio-stream-url.com/stream"; @override void initState() { super.initState(); _radioPlayer.init(_myRadioUrl); } @override void dispose() { _radioPlayer.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text("My Online Radio")), body: Center( child: ElevatedButton( onPressed: () async { await _radioPlayer.togglePlayPause(); setState(() {}); }, child: Text(_radioPlayer.isPlaying ? "Pause Radio" : "Play Radio"), ), ), ); } }
Troubleshooting Tips
- Plugin issues? Restart your app (hot reload might not pick up native permission changes) and double-check
flutter pub getran successfully. - Stream won’t play? Test your radio URL in a browser or media player first — if it fails there, the issue is with the stream itself, not your code.
- Background playback not working? Verify you added the
UIBackgroundModesentry for iOS and foreground service permissions for Android. - Audio focus problems? The
audio_sessionpackage handles this by default, but you can tweak the session configuration if you need custom behavior.
内容的提问来源于stack exchange,提问作者Sadisha

