Play a Custom Sound in Flutter - android

I'm trying to Play a custom mp3 sound I've put in an asset folder into the app folder, like you would do for a font or an image file, but then I don't really know how to proceed. I think I might need to register the audio file into the pubspec.yaml, but how?
And how do I play it?
I've checked out this two answer:
How to play a custom sound in Flutter?
Flutter - Play custom sounds updated?
But the first one is too old and the second one uses URLs as the sound path: const kUrl2 = "http://www.rxlabz.com/labz/audio.mp3"; and the sound I like to play is in the app, not online. So... How can I do it?
This Is My Current Code, as You can see, there's only a Floating Button.
And I need To Start The Sound at the Point I stated it in the code.
But visual studio underlines in red Various Parts:
await: it says that await is unrecognized.
audioPlugin.play: is says It's also unrecognized
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(new MyApp());
Directory tempDir = await getTemporaryDirectory();
File tempFile = new File('${tempDir.path}/demo.mp3');
await tempFile.writeAsBytes(bytes, flush: true);
AudioPlayer audioPlugin = new AudioPlayer();
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void _incrementCounter() {
setState(() {
print("Button Pressed");
///
///
///
/// Here I Need To start Playing the Sound
///
///
///
///
audioPlugin.play(tempFile.uri.toString(), isLocal: true);
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
}

It's not pretty, but...
Add the mp3 file to the assets folder and add it to pubspec.yaml like this.
Load the asset as binary data with rootBundle.load(asset)
Use path_provider to get the app's temp folder location
Use regular dart:io to open a file in tempDir (maybe use the asset name) and write bytes to it.
Form a file URL from the temporary file name in the form file:///folderPath/fileName
Pass this to audioplayer, setting isLocal to true (needed on iOS).
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:audioplayer/audioplayer.dart';
import 'package:path_provider/path_provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Audio Player Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
AudioPlayer audioPlugin = AudioPlayer();
String mp3Uri;
#override
void initState() {
_load();
}
Future<Null> _load() async {
final ByteData data = await rootBundle.load('assets/demo.mp3');
Directory tempDir = await getTemporaryDirectory();
File tempFile = File('${tempDir.path}/demo.mp3');
await tempFile.writeAsBytes(data.buffer.asUint8List(), flush: true);
mp3Uri = tempFile.uri.toString();
print('finished loading, uri=$mp3Uri');
}
void _playSound() {
if (mp3Uri != null) {
audioPlugin.play(mp3Uri, isLocal: true);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Audio Player Demo Home Page'),
),
body: Center(),
floatingActionButton: FloatingActionButton(
onPressed: _playSound,
tooltip: 'Play',
child: const Icon(Icons.play_arrow),
),
);
}
}

Use the audioplayers package => https://pub.dev/packages/audioplayers
Add the key to plist for iOS Support
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Add dependencies to pubspec.yaml file
audioplayers: ^0.13.2
Flutter code:
import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
class AudioTest extends StatefulWidget {
#override
_AudioTestState createState() => _AudioTestState();
}
class _AudioTestState extends State<AudioTest> {
static AudioCache _player = AudioCache();
static const _audioPath = "count_down.mp3";
AudioPlayer _audioPlayer = AudioPlayer();
Future<AudioPlayer> playAudio() async {
return _player.play(_audioPath);
}
void _stop(){
if (_audioPlayer != null) {
_audioPlayer.stop();
}
#override
void initState() {
playAudio().then((player) {
_audioPlayer = player;
});
super.initState();
}
#override
Widget build(BuildContext context) {
return homeScreen();
}
Widget homeScreen() {
return Scaffold();
//Enter your code here
}
}

Related

how can I use flutter_phone_direct_caller packages for real

I run below code but it's not working for real
import 'package:flutter/material.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: RaisedButton(
onPressed: _callNumber,
child: Text('Call Number'),
),
),
));
}
}
_callNumber() async {
const number = '+82)010-7335-7424';
print("hi"); //set the number here
bool? res = await FlutterPhoneDirectCaller.callNumber(number);
}
how can i run for real???
Should I have to build apk and run in real phone..?
I think for call dialer or Direct navigate to the dialer, the best package will be url_launcher. At first please install the package & then try the below code ---
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: ElevatedButton(
onPressed: _callNumber,
child: Text('Call Number'),
),
),
));
}
}
_callNumber() async {
const number = '+82)010-7335-7424';
print("hi"); //set the number here
if (!await launchUrl(Uri.parse("tel://$number"))) throw 'Could not launch ${Uri.parse("tel://$number")}';
}
Basically, I change the code inside the _callnumber method which is
_callNumber() async {
const number = '+82)010-7335-7424';
print("hi"); //set the number here
if (!await launchUrl(Uri.parse("tel://$number"))) throw 'Could not launch ${Uri.parse("tel://$number")}';
}

fix net::err_unknown_url_scheme whatsapp link on flutter webview

Please I want to know how to launch WhatsApp in the Flutter webview app or launch WhatsApp from the browser in Flutter, have used many codes with no errors but they do not work.Am using mac m1
and vscode
import 'package:coinpaga/Connectivity_Provider.dart';
import 'package:coinpaga/services/local_notification_service.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'homepage.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:colorful_safe_area/colorful_safe_area.dart';
/// Receive message when app is in background solution for on
message
Future<void> backgroundHandler(RemoteMessage message)async{
print(message.data.toString());
print(message.notification!.title);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
LocalNotificationServices.initialize();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => ConnectivityProvider(),
child: HomePage(),
)
],
child:MaterialApp(
title: 'coinpaga',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: ColorfulSafeArea(
color: HexColor("#2e2a42"),
top: true,
bottom: false,
left: false,
right: false,
child: HomePage(),
)
),
);
}
}
Home.dart
import 'package:coinpaga/Connectivity_Provider.dart';
import 'package:coinpaga/no_internet.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:provider/provider.dart';
class HomePage extends StatefulWidget {
// ignore: unused_field
final _flutterwebview = FlutterWebviewPlugin();
HomePage({ Key? key }) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
void initState() {
super.initState();
Provider.of<ConnectivityProvider>(context, listen:
false).startMonitoring();
}
#override
Widget build(BuildContext context) {
return pageUI();
}
#override
void dispose() {
_flutterwebview.dispose();
super.dispose();
}
}
Widget pageUI() {
return Consumer<ConnectivityProvider>(
builder: (context, model, child) {
return model.isOnline
? WebviewScaffold(
url: 'https://coinpaga.com',
withLocalStorage: true,
withJavascript: true,
scrollBar: false,
initialChild: Center(child: Text('Loading...')),
) : NoInternet();
},
);
}
// ignore: camel_case_types
class _flutterwebview {
static void dispose() {}
}
Please help me go through it.
String text = "Hello World !! Hey There";
String url = "https://wa.me/?text=${Uri.encodeFull(text)}";
if (await canLaunchUrl(Uri.parse(url))) {
await launchUrl(Uri.parse(url),
mode: LaunchMode.externalApplication);
}
First, add url_launcher, then I use this code to launch whatsapp on flutter webview and works.
WebView(
initialUrl: getUrl(_url),
javascriptMode: JavascriptMode.unrestricted,
navigationDelegate: (NavigationRequest request) async {
if (request.url
.startsWith('https://api.whatsapp.com/send?phone')) {
print('blocking navigation to $request}');
List<String> urlSplitted = request.url.split("&text=");
String phone = "0123456789";
String message =
urlSplitted.last.toString().replaceAll("%20", " ");
await _launchURL(
"https://wa.me/$phone/?text=${Uri.parse(message)}");
return NavigationDecision.prevent;
}
print('allowing navigation to $request');
return NavigationDecision.navigate;
},
)
_launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
You can use url_launcher to launch URLs.
You can give https://api.whatsapp.com/send/?phone=(phone_number) URL to launch.
For the launching the WhatsApp Website use launch('https://api.whatsapp.com/send/?phone=(phone_number)')
Make sure you give your country code without (+).

My flutter code is erroring even though the code is right

I have written my code properly and installed all packages yet it errors out for a variable.
please help me
I am using the speech to text module and have imported and installed it but it is erroring
and i am new to flutter so please help me
import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Voice',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: SpeechScreen(),
);
}
}
class SpeechScreen extends StatefulWidget {
#override
_SpeechScreenState createState() => _SpeechScreenState();
}
class _SpeechScreenState extends State<SpeechScreen> {
stt.SpeechToText _speech;
bool _isListening = false;
String _text = 'Press the button to start speaking';
double _confidence = 1.0;
#override
Widget build(BuildContext context) {
return Container();
}
}
thank you
stt.SpeechToText _speech;
You have to initialize this property or make it nullable as below
stt.SpeechToText? _speech;

how create a RIVE animation with flutter

I want to create a RIVE animation with flutter. I followed a tutorial in YouTube. I wrote the same thing but when I execute two errors is displayed
(RiveFile.import (data);
file.mainArtboard;)
Here is the code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:rive/rive.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyPage(),
);
}
}
class MyPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Using Rive'),
),
body: RocketContainer());
}
}
class RocketContainer extends StatefulWidget {
#override
_RocketContainerState createState() => _RocketContainerState();
}
class _RocketContainerState extends State<RocketContainer> {
Artboard _artboard;
RiveAnimationController _rocketController;
#override
void initState() {
_loadRiveFile();
super.initState();
}
void _loadRiveFile() async {
final bytes = await rootBundle.load('assets/rocket.riv');
final file = RiveFile.import(bytes);
setState(() {
_artboard = file.mainArtboard;
});
}
void _launch() async {
_artboard.addController(
_rocketController = SimpleAnimation('launch'),
);
setState(() => _rocketController.isActive = true);
}
void _fall() async {
_artboard.addController(
_rocketController = SimpleAnimation('fall'),
);
setState(() => _rocketController.isActive = true);
}
#override
Widget build(BuildContext context) {
return Column(
children: [
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height - 250,
child: _artboard != null
? Rive(
artboard: _artboard,
fit: BoxFit.cover,
)
: Container()),
TextButton(onPressed: () => _launch(), child: Text('launch')),
TextButton(onPressed: () => _fall(), child: Text('fall'))
],
);
}
}
errors:
The current Dart SDK version is 2.10.5.
Because animation depends on cupertino_icons >=1.0.1 which requires SDK version >=2.12.0-0 <3.0.0, version solving failed.
pub get failed (1; Because animation depends on cupertino_icons >=1.0.1 which requires SDK version >=2.12.0-0 <3.0.0, version solving failed.)
*error: Instance member 'import' can't be accessed using static access. (static_access_to_instance_member at [animation] lib\main.dart:47)
*error: The getter 'mainArtboard' isn't defined for the type 'bool'. (undefined_getter at [animation] lib\main.dart:50)
You could have a look at the example provided with the updated and latest documentation of Rive in their official Github repository.
Control playing and pausing a looping animation:
import 'package:flutter/material.dart';
import 'package:rive/rive.dart';
class PlayPauseAnimation extends StatefulWidget {
const PlayPauseAnimation({Key? key}) : super(key: key);
#override
_PlayPauseAnimationState createState() => _PlayPauseAnimationState();
}
class _PlayPauseAnimationState extends State<PlayPauseAnimation> {
// Controller for playback
late RiveAnimationController _controller;
// Toggles between play and pause animation states
void _togglePlay() =>
setState(() => _controller.isActive = !_controller.isActive);
/// Tracks if the animation is playing by whether controller is running
bool get isPlaying => _controller.isActive;
#override
void initState() {
super.initState();
_controller = SimpleAnimation('idle');
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RiveAnimation.network(
'https://cdn.rive.app/animations/vehicles.riv',
controllers: [_controller],
// Update the play state when the widget's initialized
onInit: () => setState(() {}),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _togglePlay,
tooltip: isPlaying ? 'Pause' : 'Play',
child: Icon(
isPlaying ? Icons.pause : Icons.play_arrow,
),
),
);
}
}
To play an animation from an asset bundle, use:
RiveAnimation.asset('assets/vehicles.riv'
in place of
RiveAnimation.network('https://cdn.rive.app/animations/vehicles.riv',
This line:
_controller = SimpleAnimation('idle');
attempts to play an animation called 'idle'. If your animation is named differently, try replacing the name here.

Flutter get source URL along with Text shared from web page

I am new to Flutter. I want to get the text along with its source. Currently, I am using receive_sharing_intent which is serving the purpose of TextStream and Url individually.
I want to share the copied text from the browser and keep its URL along with it.
I followed this doc hence my main.dart is same as:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
StreamSubscription _intentDataStreamSubscription;
List<SharedMediaFile> _sharedFiles;
String _sharedText;
#override
void initState() {
super.initState();
// For sharing or opening urls/text coming from outside the app while the app is in the memory
_intentDataStreamSubscription =
ReceiveSharingIntent.getTextStream().listen((String value) {
setState(() {
_sharedText = value;
});
}, onError: (err) {
print("getLinkStream error: $err");
});
// For sharing or opening urls/text coming from outside the app while the app is closed
ReceiveSharingIntent.getInitialText().then((String value) {
setState(() {
_sharedText = value;
});
});
}
#override
void dispose() {
_intentDataStreamSubscription.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
const textStyleBold = const TextStyle(fontWeight: FontWeight.bold);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: <Widget>[
Text("Shared files:", style: textStyleBold),
Text(_sharedFiles?.map((f)=> f.path)?.join(",") ?? ""),
SizedBox(height: 100),
Text("Shared urls/text:", style: textStyleBold),
Text(_sharedText ?? "")
],
),
),
),
);
}
}
Any suggestions on how to proceed to this or any Reference will work.
Thanks!!

Categories

Resources