How can I receive a callback for loop playing in Cordova media?

In my Angular JS service, I am utilizing the cordova media plugin to access media files.

MediaSrv.loadMedia(filePath, mediaSuccess, null, status).then(function(media, status, test, status1){
                    media.play({ numberOfLoops: 999 });
                    media.setVolume(volume);
                    $scope.selectedSounds[index].state = 1;
                    $scope.selectedSounds[index].mediaInstance = media;
                    $scope.someSoundsArePlaying = true;
                });
    

I have a question about how to loop play a selected file and stop it by passing the media instance to the stop function.

I attempted using the mediaSuccess callback and status callback but encountered issues with their functionality.

The service code is as follows:

'use strict';

        angular.module('MaxRelax')
          .factory('MediaSrv', function($q, $ionicPlatform, $window){
            // Service implementation here...
          });

    

Answer №1

It's great to hear that you are finding my angular service helpful.

In your example, it seems like there may be some confusion with the parameter order:

MediaSrv.loadMedia(filePath, mediaSuccess, null, status)
vs
function loadMedia(src, onError, onStatus, onStop)

By the way, the play parameter numberOfLoops doesn't appear to work (at least on my nexus4). If you want looping, you will need to call play() each time the mp3 ends.

Here is a brief example:

var myMedia = null;
MediaSrv.loadMedia(
    'sounds/1023.mp3', 
    function onError(err){ console.log('onError', MediaSrv.getErrorMessage(err)); },
    function onStatus(status){ console.log('onStatus', MediaSrv.getStatusMessage(status)); },
    function onStop(){ console.log('onError'); myMedia.play(); },
).then(function(media){
    myMedia = media;
    myMedia.play();
});

With this code, your sound should play indefinitely... To control when the sound stops, I recommend adding a control parameter like this:

var myMedia = null;
var shouldPlay = false;
MediaSrv.loadMedia(
    'sounds/1023.mp3', 
    function onError(err){ console.log('onError', MediaSrv.getErrorMessage(err)); },
    function onStatus(status){ console.log('onStatus', MediaSrv.getStatusMessage(status)); },
    function onStop(){ console.log('onError'); if(shouldPlay){myMedia.play();} },
).then(function(media){
    myMedia = media;
});

function playStart(){
    shouldPlay = true;
    myMedia.play();
}
function playStop(){
    shouldPlay = false;
    myMedia.stop();
}

To play multiple files in a loop, you will need to store all media references and play them sequentially. Here's an example:

var shouldPlay = false;
var playingMedia = null;
var soundFiles = ['sounds/1.mp3', 'sounds/2.mp3', 'sounds/3.mp3'];
var mediaInstances = [];
var onPlayStop = function(){
    if(shouldPlay){
        if(playingMedia === null){
            playingMedia = 0;
        } else {
            playingMedia = (playingMedia+1) % mediaInstances.length;
        }
        mediaInstances[playingMedia].play();
    }
};
for(var i in soundFiles){
    MediaSrv.loadMedia(soundFiles[i], null, null, onPlayStop).then(function(media){
        mediaInstances.push(media);
    });
}

function playStart(){
    shouldPlay = true;
    onPlayStop();
}
function playStop(){
    shouldPlay = false;
    mediaInstances[playingMedia].stop();
}

I hope this information proves useful! :D

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Analyzing and inserting elements into an array of objects

The following code aims to: 1) iterate through the two arrays, 2) if an item exists in both arrays, add its value to the value of the matching item in the first array, 3) if the item is found in arr2 but not in arr1, add the item to arr1. The code funct ...

When making an ajax call, I passed the data "itemShape" but on the URL page, an error appeared stating "Undefined index: itemShape"

Hello, I have been using an Ajax function to send data with the key itemShape. However, when I directly access the URL page or service page, it displays the following error: Notice: Undefined index: itemShape in C:\wamp64\www\inventory_so ...

How can we export data to excel using react-export-excel while ensuring certain columns are hidden?

Greetings! I believe the title gives you a clear idea of my dilemma. When exporting data, there are no errors - my goal is to hide the Excel column when the checkbox is unchecked or false, and display it when the checkbox is checked or true during export. ...

Django REST Framework error when uploading image: "The data provided is not a valid file"

Currently, I am in the process of learning how to upload files in Django. However, I have encountered what seems to be a simple issue with the following error message: The submitted data was not a file. Check the encoding type on the form. Below are th ...

Tips for configuring your Gruntfile and Yeoman to create a feature-focused layout in your directory

After using Yeoman's angularJS generator (yo angular) to create a new project, the app is set up with a specific directory structure: app scripts controllers aFeatureController bFeatureController directives aFeatureDi ...

AngularJS text markers

In order to streamline the process of managing tags with random content, I have devised a 'tag' manipulation system using the angular-ui alert mechanism. The system includes a factory and a directive as follows: Factory: app.factory( &a ...

Issue with child component validation in VueJS 2 and vee-validate 3: not functioning as expected

Current vee-validate version: 3.4.5 I have a FormBuilder.vue component that constructs my form inputs schema accordingly. Within this component, I have a custom InputSlugify component and I am looking to implement vee-validate validation for it using the ...

"Using conditional statements to check for specific value ranges and properly handling cases where the result is undefined

Currently, I am working on a function that prompts the user to input a number and then displays a calculated score after they click a button. The score is based on the value entered by the user. While constructing this feature, I have pondered whether IF ...

Identifying DNS lookup errors in JavaScript: A beginner's guide

Is there a method to identify DNS lookup errors through JavaScript? Are there any code snippets or techniques that can achieve this? Is it a challenging task or is there a solution available? If anyone can provide some insight on this, I would greatly a ...

Specifying the data type for a "promisifier" function in TypeScript or Flow

I have developed a function that effectively converts a callback-style function in Node.js to a promise-style function. export const promisify : PromisifyT = ( fn, ...args ) => { return new Promise( (resolve, reject) => { ...

How can one access the precise and straightforward code for implementing the Facebook pixel?

(I am continuously refining this question, feel free to help me articulate it better. I have provided my own answer to assist in framing the question more effectively) Explicit - in this context, means "direct". The code provided by Facebook is minified a ...

Error in Java program: java.lang.RuntimeException occurred due to inability to instantiate the activity ComponentInfo and the class was not found

To resolve the errors stated: - Ensure to import the app support libraries as projects from sdk/extras/android/support/v7 But now I am encountering this issue: 12-04 05:54:16.067: E/AndroidRuntime(1749): FATAL EXCEPTION: main 12-04 05:54:16.067: E/An ...

Reorder div elements using jQuery with two specific criteria

On my website, I have implemented a method for sorting divs (.ligne) with different sorting options: by name, date, status, and type. The jQuery code I've written works well, but I want to refine it further to make it lighter. When clicking on each h ...

Having issues with the Vuetify component, specifically the v-date-picker not functioning properly

Hey there! I'm still getting the hang of vuetify and have been experimenting with creating functions using simple components. One such component I've been using is v-date-picker. However, I've encountered an issue where the calendar doesn&a ...

Is there a feature in Angular JS similar to dojo.hitch()?

I apologize for my lack of knowledge in AngularJS. I am wondering if there exists a similar function to dojo.hitch() within AngularJS. dojo.hitch() returns a function that is ensured to be executed in the specified scope. ...

Executing tests with Protractor and Appium across various devices

I am experimenting with running protractor tests on multiple devices. Testing on various desktop browsers Using Appium to test on different mobile browsers The configurations for desktop and mobile browser testing using Appium are distinct. Is it possib ...

Geofencing in Phonegap is plugin that allows for precise location

Has anyone successfully implemented a phonegap geofencing plugin? I have been unable to install the ones I've come across, and they are only cordova plugins, not specifically for phonegap. I believed it would work, but unfortunately, it does not. Edi ...

Is there a neat method in React and Material UI for de-structuring the props that I am passing to useStyles?

When passing props to useStyles based on the Material docs, our code looks like this: const useStyles = makeStyles({ // style rule foo: props => ({ backgroundColor: props.backgroundColor, }), bar: { // CSS property color: props => ...

Setting up Android Constraint Layout on your device

Every time I attempt to compile my project, a message pops up indicating that I need to install Constraintlayout. But, when I try to do so, the installation process fails and this is the output: To install: - Solver for ConstraintLayout 1.0.2 (extras ...

The Express.io platform is having trouble loading the JavaScript file

Currently, I have an operational Express.io server up and running. However, I am encountering issues with the proper loading of my Javascript files. Here is a snippet from my Jade file: html head h1 Test index body script(src="/so ...