Event 'PlaybackQueueEnded' is not fired in React Native Track Player - react-native

I am using react-native-track-player package to play music files in my React Native mobile application.
There due to some issue, I need to stop the track-player once the queue of audio tracks reaches the end. For that, I use the event PlaybackQueueEnded to invoke the following code snippet. (I have used it in the useTrackPlayerEvents hook along with the PlayerTrackChanged event which when fired, sets the title, author, and background of the current audio file being played).
useTrackPlayerEvents(
// To set the title, author, and background of the current audio file being played
[Event.PlaybackTrackChanged, Event.PlaybackQueueEnded],
async event => {
if (
event.type === Event.PlaybackTrackChanged &&
event.nextTrack !== null
) {
const track = await TrackPlayer.getTrack(event.nextTrack);
const title = track?.title;
const artist = track?.artist;
const artwork: SetStateAction<any> = track?.artwork;
setTrackTitle(title);
setTrackArtist(artist);
setTrackArtwork(artwork);
}
// To stop the player once it reaches the end of the queue
if (
event.type === Event.PlaybackQueueEnded &&
event.position === progress.duration
) {
TrackPlayer.stop();
}
},
);
But the above code doesn't work as I expected. Seems the event PlaybackQueueEnded is not fired when playing the last track of the queue. Can somebody please help me to solve this issue?
Thank you.
PS: I am taking the current time and duration of the audio file being played by using the useProgress hook and have assigned its value to the progress variable. By that, I'm taking progress.position and progress.duration.

PlaybackQueueEnded will be fired when the song is finished and you dont need to check if event.position === progress.duration

Related

How to remove a specific notification forever using react-native-push-notification

I am currently using the react-native-push-notification library to schedule and receive notifications in my React Native app. I am able to cancel a scheduled notification using the cancelLocalNotification method, but this only cancels the notification for 24 hours. I want to find a way to remove a specific notification forever, so it will not be rescheduled.
I have tried using the following code to cancel a notification by its ID, but it only cancels it for 24 hours:
const onCancelNotification = async (id: string) => {
// Get a list of all scheduled notifications
PushNotification.getScheduledLocalNotifications((notifications) => {
// Iterate through the list of notifications
notifications.forEach((notification) => {
// Check if the notification is the one you want to cancel
if (notification.id.indexOf(id) === 0) {
// Cancel the notification
PushNotification.cancelLocalNotification(notification.id);
}
});
});
};
I would greatly appreciate any help or suggestions on how to achieve this.
This code snippet demonstrates a workaround for removing a specific scheduled local notification in React Native. The function onRemoveNotification takes in an id parameter, which is used to identify the specific notification that needs to be removed.
It's important to note that there is no direct method for removing a specific scheduled local notification in React Native. This code provides a workaround that can be used, but it's important to be aware that it relies on scheduling a notification with an earlier date and setting the repeatType to undefined.
Please note that this code is not a perfect solution and could have side effects on the app.
const onRemoveNotification = async (id: string) => {
// Get a list of all scheduled notifications
PushNotification.getScheduledLocalNotifications((notifications) => {
// Iterate through the list of notifications
notifications.forEach((notification) => {
// Check if the notification is the one you want to cancel
if (notification.data.notificationId?.indexOf(id) === 0) {
// Create a new date one day earlier than the current scheduled date
const earlyDate = moment(notification.date).add(-1, "day").toDate();
// remove the notification
// schedule the notification with an earlier date and repeat type undefined
// this will effectively "remove" the notification
// since it will not be displayed
PushNotification.localNotificationSchedule({
id: notification.id,
title: notification.title,
message: notification.message,
repeatType: undefined,
date: earlyDate,
});
// cancel the previous scheduled notification
PushNotification.cancelLocalNotification(notification.id);
}
});
});
};

anchor or completion for logging events

I'm using react native 0.61.5 with react-native-branch
I followed this tutorial as integration guide : https://blog.reactnativecoach.com/how-to-create-a-referall-system-using-branch-io-in-react-native-6f9f924149e0
is there a way when I use the branch.userCompletedAction() to get a completion or an anchor that the process has been done?
I need to fetch the credits as soon as the event has been logged.
this is my code :
export const logBranchEvent = async (
eventName,
eventParams,
) => {
if (loggedToBranch) {
await branch.userCompletedAction(eventName, eventParams);
const res = await branch.loadRewards();
console.log(res.credits)
}
};
I get that there are 0 credits but when I wait and the check the credits I get the proper amount of credits.
thanks
We do not have a callback for branch.userCompletedAction() method. This method is used to log events.
You can try to fetch the rewards when the action is completed. It would not take more than 2 seconds. That would be best possible approach here.
Let me know if you would need further information here.

WebRTC: Detecting muted track faster post warm-up

I'm warming up my transceiver like so:
pc.addTranceiver('video')
This creates a dummy track in the transceiver's receiver. Soon after, the unmute event fires on that track.
Then, ~3 seconds later, the mute event fires.
My goal is to detect that a track is a dummy track as fast as possible.
ideas
send a message via the data channel telling the peer that the track is void. this is a pain since i'll have to send another message when I later call replaceTrack
write a frame of the track to canvas & see if it's an image. This seems really barbaric, but it's faster than 3 seconds.
anything better? it feels like this should be pretty simple.
This is a bug in Chrome (please ★ it so they'll fix it).
The spec says receiver tracks must start out muted and should stay that way until packets arrive. But Chrome fires the unmute event immediately, followed a few seconds later by a mute event due to inactivity (another bug):
const config = {sdpSemantics: "unified-plan"};
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
pc1.addTransceiver("video");
pc2.ontrack = ({track}) => {
console.log(`track starts out ${track.muted? "muted":"unmuted"}`);
track.onmute = () => console.log("muted");
track.onunmute = () => console.log("unmuted");
};
pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc1.onnegotiationneeded = async e => {
await pc1.setLocalDescription(await pc1.createOffer());
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription(await pc2.createAnswer());
await pc1.setRemoteDescription(pc2.localDescription);
}
In Chrome you'll see incorrect behavior:
track starts out muted
unmuted
muted
In Firefox you'll see correct behavior:
track starts out muted
Chrome workaround:
Until Chrome fixes this, I'd use this workaround:
const video = document.createElement("video");
video.srcObject = new MediaStream([track]);
video.onloadedmetadata = () => log("unmuted workaround!");
Until this fires, assume the track to be muted.

VueJs Progress Bar to track VueX mutation progress

I'm having an issue creating a Progress bar that tracks the real time progress of a VueX mutation.
I have a button component that runs a mutation when the user clicks the button. This mutation goes through an array and performs a function on each item in the array. While performing this function it updates a 'progress' status in the store. I have a progress bar component that reads this 'progress' status from the store as a computed property.
I was hoping that as the progress status updates so would the progress bar but it seems I am having an issue with the DOM Rendering the change as quickly as it is being updated. My mutation runs and the progress bar goes from 0 to 100 with no update in-between.
I guess I'm having an issue conceptualizing why my DOM isn't redrawing as quickly as I am updating the 'progress' status and if there is any way of accomplishing this
I've found that the 'For' loop I use to process my array 'freezes' the dom and stops it from re-rendering. To fix this I've used a 'setTimeout' call. This seems like a hack but will hopefully help someone else who comes up against this issue. More answers appreciated. thanks to #Eric Guan for putting me down this path. I found the answer on another post here -> How to stop intense Javascript loop from freezing the browser
var self = this;
var animals = ['dog', 'cat','lion','tiger','bear'];
var processing = function() {
var animal = animals.shift();
console.log(animal);
if (animals.length > 0) {
console.log(animals.length);
var timer = setTimeout(processing, 1000);
self.$store.commit('updateStatus', {progress : animals.length*20, msg: 'Progress Bar Test', status: 'processing', display: true});
} else {
console.log('clearing timeout');
self.$store.commit('updateStatus', {progress : 100, msg: 'Progress Bar Test', status: 'processing', display: false});
clearTimeout(timer);
}
}
processing();

It is so slow when a callback function be called repeatedly in react native app

It will have a callback function called repeatedly to when I start a download task. But It will be so slow that it can't give feedback when touch a button.
Fileio.downloadFile(downloadData[downloadFileIndex].uri, '1.jpg',this.progressFunc.bind(this)).then((DownloadResult)=> {
if (DownloadResult.statusCode == 200) {
let nextDownloadFileIndex = this.props.downloadFileIndex + 1;
this.props.dispatch(DOWNLOADED_A_FILE({
downloadFileIndex:nextDownloadFileIndex,
progressNum:0
}))
}
}).catch((error)=> {
console.log(error)
})
This is my code and the callback function are as be folllowed
progressFunc(DownloadBeginCallbackResult) {
let progressNum = DownloadBeginCallbackResult.bytesWritten / DownloadBeginCallbackResult.contentLength;
if(progressNum<=0.99){
this.props.dispatch(DOWNLOADING_A_FILE({
progressNum:progressNum,
jobId:this.props.jobId
}));
}else{
this.props.dispatch(DOWNLOADING_A_FILE({
progressNum:0,
jobId:this.props.jobId
}));
}
}
I mean I can't get feedback immediately when I touch button. I think that it is because I have a callback function called repeatedly. so js can't handle so many tasks;
It does sound like JS thread is busy doing the request and not able to communicate back to UI thread. One thing you can try is to wrap you on press handler in an InteractionManager.runAfterInteractions(() => ...)
See https://facebook.github.io/react-native/docs/interactionmanager.html