I am currently using audioplayers: ^0.20.1 to play and resume the video, right now I would like to loop the audio 3 times (keep looping to play the audio). As I know audioplayers package has loop property but I still don't know how to custom the loop property
Here is how you can loop the audio player:
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: AudioPlayerLoopTesting()));
}
class AudioPlayerLoopTesting extends StatefulWidget {
#override
_AudioPlayerLoopTestingState createState() => _AudioPlayerLoopTestingState();
}
class _AudioPlayerLoopTestingState extends State<AudioPlayerLoopTesting> {
AudioCache audioCache = AudioCache();
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
void _playLoopAudio() {
int timesPlayed = 0;
const timestoPlay = 3;
//audio.mp3 is the local asset file
audioCache.play('audio.mp3').then((player) {
player.onPlayerCompletion.listen((event) {
timesPlayed++;
if (timesPlayed >= timestoPlay) {
timesPlayed = 0;
player.stop();
} else {
player.resume();
}
});
});
}
Widget localAsset() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Loop Local Asset'),
ElevatedButton(
child: const Text('Loop the audio'),
onPressed: _playLoopAudio,
),
],
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: localAsset(),
),
);
}
}
Thumbs up if problem resolved
to loop the audio try this :-
static AudioCache musicCache;
static AudioPlayer instance;
void playLoopedMusic() async {
musicCache = AudioCache(prefix: "audio/");
instance = await musicCache.loop("bgmusic.mp3");
// await instance.setVolume(0.5); you can even set the volume
}
void pauseMusic() {
if (instance != null) {
instance.pause(); }}
to loop it 3 time only :-
int numberOftimesToPlay=0;
playThreeTimes(){
_audioPlayer = AudioPlayer();
int res = await _audioPlayer.play("https://192.168.1.66/$sUrl");
//await _audioPlayer.play("http://192.168.1.5/00001.mp3");
if (res == 1 & numberOftimesToPlay>4) {
numberOftimesToPlay ++;
playThreeTimes()
print("ok");
} else {
print("done");
}}
Related
I am trying for the past two days to Get user data from binance Api with the Binance test net key using package https://pub.dev/packages/binance_spot/example
I tried every way possible I learned as I am a beginner I am not able to get the user data from the user account
I also changed the links that work for the testnet finance API version
here is the example code snippet
import 'dart:async';
import 'package:binance_spot/binance_spot.dart';
import 'package:flutter/material.dart' hide Interval;
class BinanceScreen extends StatefulWidget {
const BinanceScreen({Key? key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<BinanceScreen> {
BinanceSpot binanceSpot = BinanceSpot(
key: "3HKUUgtwu8WFWh4q31C5bh1veQqMEkEbF07hpMrq8xnwYsWDnj0ZWgYQkvC3gnE0",
secret: "KWwvWOi4nu8s0Qsi87iJ523cfp9Jcl8mFwt2hZHptMyahhGsxnmvdURIxVa9zA74",
);
double lastClosePrice = 0;
String tradablePairs = "";
String lastEventData = "";
WsAccountUpdate? balance;
late StreamSubscription<dynamic> klineStreamSub;
late StreamSubscription<dynamic> userdataStreamSub;
#override
void initState() {
startKlineStream();
startUserdataStream();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Binance API tester"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text("Current BTC price : $lastEventData"),
// Text("Last userdataStream event : ${balance}"),
TextButton(
onPressed: getTradablePairs,
child: const Text("GET PAIRS"),
),
Expanded(
flex: 1,
child: SelectableText(
tradablePairs,
maxLines: 200,
minLines: 1,
),
),
],
),
),
);
}
void startKlineStream() {
var stream = binanceSpot.klineStream(
symbol: "BTCUSDT",
interval: Interval.INTERVAL_5m,
);
klineStreamSub = stream.listen(handleNewKline);
}
void handleNewKline(WsKlineEvent event) {
setState(() {
lastClosePrice = event.kline.close;
});
}
void startUserdataStream() async {
var response = await binanceSpot.createListenKey();
if (response.isRight) {
var stream = binanceSpot.userDataStream(listenKey: response.right);
userdataStreamSub = stream.listen(handleUserdataEvent);
} else {
lastEventData = response.left;
}
}
void handleUserdataEvent(dynamic event) {
if (event is WsAccountUpdate) {
lastEventData =
"Account update event : ${event.balances.length} balances updated";
} else if (event is WsBalanceUpdate) {
lastEventData = "Balance update event : ${event.asset} balance updated";
} else if (event is WsExecutionReport) {
lastEventData =
"Execution report event : status is ${event.orderStatus.toStr()}";
} else if (event is WsListOrderStatus) {
lastEventData =
"ListOrder update event : status is ${event.listOrderStatus}";
} else {
lastEventData = "Unknown event type : ${event.toString()}";
}
}
void getTradablePairs() async {
var response = await binanceSpot.exchangeInfo();
if (response.isLeft) {
tradablePairs = response.left;
} else {
var listSymbol = response.right.symbols.map((e) => e.symbol).toList();
tradablePairs = "";
for (var s in listSymbol) {
tradablePairs += "$s ";
}
}
}
#override
void dispose() {
klineStreamSub.cancel();
userdataStreamSub.cancel();
super.dispose();
}
}
and here is the class code snippet which I want to acess
class WsOcoOrder {
String symbol;
int orderId;
String clientOrderId;
WsOcoOrder.fromMap(Map m)
: symbol = m['s'],
orderId = m['i'],
clientOrderId = m['c'];
}
What is the Possible way to access this class and its data in the above-given code snippet
Please refer me to the solution or a Link from where I can learn and implement by myself
Here I have an error when I fetch data, I take a reference from youtube then I apply and use data from local but when I run it I get an error as I described. here is my source code
Controller.dart
class ProdukKonvensionalController extends GetxController {
var konvenList = <ProdukKonvenModel>[].obs;
var isLoading = true.obs;
#override
void onInit() {
super.onInit();
fetchKonven();
}
Future<void> fetchKonven() async {
final response =
await http.get(Uri.parse('http://192.168.100.207:8080/konven'));
if (response.statusCode == 200) {
ProdukKonvenModel _produkkonvenModel =
ProdukKonvenModel.fromJson(jsonDecode(response.body));
konvenList.add(ProdukKonvenModel(
kategoriNama: _produkkonvenModel.kategoriNama,
kategoriId: _produkkonvenModel.kategoriId,
kontenId: _produkkonvenModel.kontenId,
kontenMenu: _produkkonvenModel.kontenMenu,
kontenParent: _produkkonvenModel.kontenParent,
kontenUrl: _produkkonvenModel.kontenUrl,
));
isLoading.value = true;
} else {
Get.snackbar("Error Loading Data",
'Server Responded: ${response.statusCode}:${response.reasonPhrase.toString()}');
}
}
}
PageView.dart
class ProdukKonvensionalPage extends StatelessWidget {
const ProdukKonvensionalPage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final _controller = Get.find<ProdukKonvensionalController>();
return Scaffold(
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('${_controller.konvenList[0].kategoriNama}'),
],
)),
);
}
}
and the following shows an error
try this
var konvenList = <ProdukKonvenModel>[].obs;
var isLoading = true.obs;
#override
void onInit() {
super.onInit();
fetchKonven();
}
Future<void> fetchKonven() async {
final response = await http.get(Uri.parse('http://192.168.100.207:8080/konven'));
if (response.statusCode == 200) {
ProdukKonvenModel _produkkonvenModel =
ProdukKonvenModel.fromJson(jsonDecode(response.body));
_produkkonvenModel.forEach((element) => konvenList.add(element));
isLoading.value = true;
} else {
Get.snackbar("Error Loading Data",
'Server Responded:
${response.statusCode}:${response.reasonPhrase.toString()}');
}
}
}
I'm going to make an app that plays a list of images and audio in order. After audio playback, the following images and audio are played.
I update image to setState() when the playback is completed. And each time use setState(), I used play() function inside the build() method to recall play().
However, the method in the build is called twice, so the audio file is also played twice.
How do I run this method only once when I build it?
class PlayingScreen extends StatefulWidget {
final PostModel postModel;
PlayingScreen({
Key? key,
required this.postModel,
}) : super(key: key);
#override
State<PlayingScreen> createState() => _PlayingScreenState();
}
class _PlayingScreenState extends State<PlayingScreen> {
final _audioPlayer = AudioPlayer();
List<String> _audios = []; // audio file path list
int _playIndex = 0;
#override
void initState() {
_getAudios();
super.initState();
}
#override
void dispose() {
_audioPlayer.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
_play(_playIndex);
return Scaffold(
appBar: AppBar(
title: Text(widget.postModel.title),
),
body: InkWell(
onTap: () {
Get.back();
},
// image widget
),
),
);
}
Future _play(int index) async {
await _audioPlayer.play(DeviceFileSource(_audios[index]));
logger.d("current index: $_playIndex / ${_audios.length - 1}");
//complete event
_audioPlayer.onPlayerComplete.listen((event) {
logger.d("complet, next");
setState(() {
if (_playIndex >= _imageSets.length - 1) {
_playIndex = 0;
logger.d("return first index");
} else {
_playIndex++;
}
});
});
}
}
// ...
int _playIndex = 0;
bool played = false
// ...
// build
if(! played) {
_play(_playIndex);
played = true;
}
Add the variable "played" at the class level
Add a check in the build method
Calling a future inside the build method will always rebuild multiple times not only twice.
I would probably use it in a FutureBuilder() like so:
FutureBuilder(
future:_play(_playIndex),
builder:(context, snapshot){
...
}
)
I'm new in flutter development and I got stuck in a program where I want to play an audio file by selecting it from file manager.i am able to open audio file from file manager but I don't know how to play that audio file.
Please help me out with this.
I am using this code -
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class FilePickerDemo extends StatefulWidget {
#override
_FilePickerDemoState createState() => _FilePickerDemoState();
}
I am using this for file picking and save file I want to know how to play save file
class _FilePickerDemoState extends State<FilePickerDemo> {
void _pickFiles() async {
_resetState();
try {
_directoryPath = null;
_paths = (await FilePicker.platform.pickFiles(
type: _pickingType,
allowMultiple: _multiPick,
onFileLoading: (FilePickerStatus status) => print(status),
allowedExtensions: ['mp3'],
))
?.files;
} on PlatformException catch (e) {
_logException('Unsupported operation' + e.toString());
} catch (e) {
_logException(e.toString());
}
if (!mounted) return;
setState(() {
_isLoading = false;
_fileName =
_paths != null ? _paths!.map((e) => e.name).toString() : '...';
_userAborted = _paths == null;
});
}
You can use https://pub.dev/packages/just_audio package to play audio.
import 'package:just_audio/just_audio.dart';
final _player = AudioPlayer();
playAudio() async {
try {
await _player.setFilePath(widget.audioPath);
} catch (e) {
log("Error loading audio source: $e");
}
_player.play();
}
Another handy package is AudioPlayers that can also cache local audio files.
Here is a very basic example, that has buttons to play, pause and stop a reference to local audio that is passed into a stateful widget, to get you started (based mainly off this Medium article) Medium Article
Reminder to save your audio in your local files like below
and add a reference in your yaml file and get dependencies
assets:
- assets/audio/
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
class AudioManagerExample extends StatefulWidget {
const AudioManagerExample({required this.audioName, Key? key}) : super(key: key);
final String audioName;
#override
_AudioManagerExampleState createState() => _AudioManagerExampleState();
}
class _AudioManagerExampleState extends State<AudioManagerExample> {
AudioPlayer audioPlayer = AudioPlayer();
late AudioCache audioCache;
#override
void initState() {
audioCache = AudioCache(fixedPlayer: audioPlayer);
audioCache.load('audio/${widget.audioName}.mp3');
super.initState();
}
#override
void dispose() {
audioCache.clearAll();
audioPlayer.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
setState(() {
audioCache.play('audio/${widget.audioName}.mp3');
});
},
child: Text('Play ${widget.audioName}'),
),
ElevatedButton(
onPressed: () {
setState(() {
audioPlayer.pause();
});
},
child: Text('Pause ${widget.audioName}'),
),
ElevatedButton(
onPressed: () {
setState(() {
audioPlayer.stop();
});
},
child: Text('Stop ${widget.audioName}'),
),
],
);
}
}
I have been trying to run the multiple audio files at the same time each having a separate mute button. I have tried AudioPlayer Flutter plugin.
I have tried the following code but it makes the files run one by one, not simultaniously.
Please help!!
Future play() async {
await audioPlayer.play(url);
await audioPlayer2.play(url2);
setState(() {
playerState = AudioPlayerState.PLAYING;
});
}
May be their are more appropriate solutions but this solved my problem at the moment, I have used the plugin audioplayers and created multiple instances for each audio file.
Updated: For example for two audio files it's done like below:
enum PlayerState { stopped, playing, paused }
enum PlayerState1 { stopped1, playing1, paused1 }
class AudioScreen extends StatefulWidget {
#override
_AudioScreenState createState() =>_AudioScreenState();
}
class _AudioScreenState extends State<AudioScreen> {
//for first audio
AudioPlayer audioPlayer;
PlayerState playerState = PlayerState.stopped;
get isPlaying => playerState == PlayerState.playing;
//for second audio
AudioPlayer audioPlayer1;
PlayerState1 playerState1 = PlayerState1.stopped1;
get isPlaying1 => playerState1 == PlayerState1.playing1;
#override
void initState() {
super.initState();
audioPlayer = new AudioPlayer();
audioPlayer1 = new AudioPlayer();
}
Future play() async {
await audioPlayer.play(url);
setState(() {
playerState = PlayerState.playing;
});
await audioPlayer1.play(url1);
setState(() {
playerState1 = PlayerState1.playing1;
});
}
Future stop() async {
await audioPlayer.stop();
setState(() {
playerState = PlayerState.stopped;
});
await audioPlayer1.stop();
setState(() {
playerState1 = PlayerState1.stopped1;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body:Column(
children:[
IconButton(
onPressed:() play(),
iconSize: 70.0,
icon:Icon(Icons.play_circle_outline, size: 55),
),
IconButton(
onPressed: stop(),
iconSize: 55.0,
icon: Icon(Icons.stop),
),
]
),
);
}
}
This way you can multiple instances or just use a loop to create multiple instances for each audio.