how use funtion rate in audio_service flutter - flutter

I'm creating an audio player and I already have most of its functionality; however, I need the function to speed up the audio playback. I cannot find that function in the package I'm using.
If anyone knows of any tutorial on how to use this function to speed up the audio speed, I would appreciate it.

audio_service 0.17 and earlier
In the UI:
await AudioService.setSpeed(1.8); // 1.8x speed
In your background task:
#override
Future<void> onSetSpeed(double speed) => _audioPlayer.setSpeed(speed);
These work just like seekTo and onSeekTo in the project example (which you can use as a guide), except that the parameter represents the speed rather than the seek position.
audio_service 0.18 and later
In the UI:
await audioHandler.setSpeed(1.8); // 1.8x speed
In your audio handler:
#override
Future<void> setSpeed(double speed) => _audioPlayer.setSpeed(speed);

/// Sets the playback rate - call this after first calling play() or resume().
///
/// iOS and macOS have limits between 0.5 and 2x
/// Android SDK version should be 23 or higher.
/// not sure if that's changed recently.
Future<int> setPlaybackRate({double playbackRate = 1.0}) {
return _invokeMethod('setPlaybackRate', {'playbackRate': playbackRate});
}
you can try like this or not?
audioplayers: ^0.16.1

Related

why camera from my doc is different to the example

I followed a tutorial and code looks like this:
class MyGame extends Forge2DGame{
#override
Future<void> onLoad() async {
camera.toString(); // <= this camera is a Vector2
}
}
But what I learned from another tutorial is like this:
class SpacescapeGame extends FlameGame{
#override
Future<void> onLoad() async {
camera.shake(); // <= this camera is a Camera class
}
}
What I understand is Forge2DGame extends BaseGame, BaseGame extends FlameGame https://pub.dev/documentation/bonfire/latest/base_base_game/BaseGame-class.html
but why I cant use camera.shake as second tutorial showed? thank you for your explanation!
I recommend that you read the Flame documentation instead of the bonfire documentation if you want to write a Flame game that is not involving bonfire.
The camera for Forge2DGame is the same camera as is used for FlameGame, you have most likely added some other variable that is also called camera which is shadowing the real camera.
Also make sure that you are on the latest version of flame (1.4.0) and the latest version of flame_forge2d (0.12.3).

Flutter video_player Duration?

I am using the Flutter video_player package here: https://pub.dev/packages/video_player
How do I get the duration of the video? I can see there is a position property, so I would need that to get the current value in time.
But how do I get the total duration of the video? The video is from a URL.
I am making a custom player so I need these two values.
For getting the Total duration you can use the video controller
VideoPlayerController _controller = VideoPlayerController.network('https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4')
..initialize().then((_) {
// Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
});
Duration durationOfVideo = _controller.value.duration;
You can also directly store the integer instead of duration as below image
You can create a function to calculate the video Dutarion and format it.
getVideoPosition() {
var duration = Duration(milliseconds: videoController.value.position.inMilliseconds.round());
return [duration.inMinutes, duration.inSeconds].map((seg) => seg.remainder(60).toString().padLeft(2, '0')).join(':');
}
After craeate this function, you just need to call it to show the duration.
Ex.:
Text(getVideoPosition())

Stream synthetized audio in real time in flutter

I'm trying to create an app generating a continuos sinewave of various frequency (controlled by the user) and I'm trying to play the data as it's generated in real time.
I'm using just_audio right now to play bytes generated using wave_generator, as follows (snippet from issue):
class BufferAudioSource extends StreamAudioSource {
final Uint8List _buffer;
BufferAudioSource(this._buffer) : super(tag: "Bla");
#override
Future<StreamAudioResponse> request([int? start, int? end]) {
start = start ?? 0;
end = end ?? _buffer.length;
return Future.value(
StreamAudioResponse(
sourceLength: _buffer.length,
contentLength: end - start,
offset: start,
contentType: 'audio/wav',
stream: Stream.value(List<int>.from(_buffer.skip(start).take(end - start))),
),
);
}
}
And I'm using the audio source like this:
StreamAudioSource _source = BufferAudioSource(_data!);
_player.setAudioSource(_source);
_player.play()
Is there a way I could feed the data to the player as soon as I generate it on the fly, using a sinewave generator, so that if the user changes the frequency, the playback will reflect the change as soon as it happens?
I tried looking online and on the repository github but I couldn't find anything.

Flutter Audioplayers delay

I'm coding a small game with the Flutter Framework.
I'm using audioplayers for the Sounds.
It works fine like this, when calling it for example 2 times a second.
But whenn I call it more than 5 times and again in the next second at some point the sound has like a delay and then after a second or so all the sounds play at once :) That sounds weired.
I also tested the audioplayers example from github on my iphone. Repeating the sounds in low frequency is ok, but when I repeat clicking the button as fast as possible at some point it gets some delay and the same thing is happening.
Is there some way to stop the previous Sound before and then playing the next one or isnt this possible?
Or is there some other Idea how to deal with the sounds?
This is how I use it:
AudioCache upgradeSound = new AudioCache();
void playUpgradeSound() {
_playUpgradeSound(upgradeSound);
}
void _playUpgradeSound(AudioCache ac) async{
await ac.play('audio/upgr.mp3');
}
Thank you very much in advance
I solve similar problem by having singleton class, and after first play I can get the state, and I can stop previous play.
class Audio {
static final playerCache = AudioCache();
static AudioPlayer audioPlayer;
static void play(String audioName) async {
audioPlayer = await playerCache.play('$audioName.mp3');
}
static void stop() {
audioPlayer.stop();
}
}
...
child: IconButton(
onPressed: () {
try {
if (Audio.audioPlayer.state ==
AudioPlayerState.PLAYING) {
Audio.stop();
} else {
Audio.play('bid');
}
} catch (e) {
Audio.play('bid');
}
},
...
There is a line of code in its own documentation.
To use the low latency API, better for gaming sounds, use:
AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.LOW_LATENCY);
In this mode the backend won't fire any duration or position updates. Also, it is not possible to use the seek method to set the audio a specific position. This mode is also not available on web.
I hope it is useful.

how to run vibrate continuously in iphone?

In my application I'm using following coding pattern to vibrate my iPhone device
Include: AudioToolbox framework
Header File:
#import "AudioToolbox/AudioServices.h"
Code:
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
My problem is that when I run my application it gets vibrate but only for second but I want that it will vibrate continuously until I will stop it.
How could it be possible?
Thankfully, it's not possible to change the duration of the vibration. The only way to trigger the vibration is to play the kSystemSoundID_Vibrate as you have. If you really want to though, what you can do is to repeat the vibration indefinitely, resulting in a pulsing vibration effect instead of a long continuous one. To do this, you need to register a callback function that will get called when the vibration sound that you play is complete:
AudioServicesAddSystemSoundCompletion (
kSystemSoundID_Vibrate,
NULL,
NULL,
MyAudioServicesSystemSoundCompletionProc,
NULL
);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
Then you define your callback function to replay the vibrate sound again:
#pragma mark AudioService callback function prototypes
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
);
#pragma mark AudioService callback function implementation
// Callback that gets called after we finish buzzing, so we
// can buzz a second time.
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
) {
if (iShouldKeepBuzzing) { // Your logic here...
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
} else {
//Unregister, so we don't get called again...
AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
}
}
There are numerous examples that show how to do this with a private CoreTelephony call: _CTServerConnectionSetVibratorState, but it's really not a sensible course of action since your app will get rejected for abusing the vibrate feature like that. Just don't do it.
Read the Apple Human Interaction Guidelines for iPhone. I believe this is not approved behavior in an app.
iOS 5 has implemented Custom Vibrations mode. So in some cases variable vibration is acceptable. The only thing is unknown what library deals with that (pretty sure not CoreTelephony) and if it is open for developers. So keep on searching.
The above answers are good and you can do it in a simple way also.
You can use the recursive method calls.
func vibrateTheDeviceContinuously() throws {
// Added concurrent queue for next & Vibrate device
DispatchQueue.global(qos: .utility).async {
//Vibrate the device
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
self.incrementalCount += 1
usleep(800000) // if you don't want pause in between, remove this line.
do {
if let isKeepBuzzing = self.iShouldKeepBuzzing , isKeepBuzzing == true {
try self.vibrateTheDeviceContinuously()
}
else {
return
}
} catch {
//Exception handle
print("exception")
}
}
}
To stop the device vibration use the following line.
self.iShouldKeepBuzzing = false
ios swift