How to getCurrentPosition in Cordova Plugin Media?


#1

Hello guys,

I’m new to Ionic 2 + Angular 2 just week. And I’m stucking on getCurrentPosition method from Cordova Plugin Media. Play and Pause are working great, excluding getCurrentPosition. Anyone can give a help? I embeded the code below.

Thanks in advance.

import { Component } from '@angular/core';
import {NavController} from 'ionic-angular';
import {MediaPlugin} from 'ionic-native';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
	private _music: MediaPlugin;
	mediaTimer: any;
	isPlaying = false;

  constructor(navController: NavController) {
  }
  
    public clickMusic() { // Working great
	    if ( this._music == null ) {
		    this._music = new MediaPlugin('http://www.domain.com/audio.mp3');
        	this.playMusic();
        }
        else {
	        if ( this.isPlaying ) {
		        this._music.pause();
		        this.isPlaying = false;
	        }
	        else {
		        this.playMusic();
	        }
        }   
    }
    
    public playMusic() {
    	this._music.play();
    	this.isPlaying = true;
    	
    	this.showProgress(); // get getCurrentPosition
    }
    
    public showProgress() { // THIS IS NOT WORKING
		this.mediaTimer = setInterval(function () {
		    // get media position
		    this.getCurrentPosition(
		        // success callback
		        function (position) {
		            if (position > -1) {
		                alert((position) + " sec"); // THIS IS NOT WORKING
		            }
		        },
		        // error callback
		        function (e) {
		            alert("Error getting pos=" + e);
		        }
		    );
		}, 1000);
    }
    
}

#2

According to the source, getCurrentPosition returns a promise, so you don’t want to be passing callbacks to it. Just do:

this._music.getCurrentPosition().then((curpos) => {
  // do whatever with curpos
});

#3

Hi rapropos,

Thank you for fast reply. It works great. You made my day! Here is my code to show timer variable to view file. Is it not bad code for performance?

Cheers!

public showProgress() {
    var self = this;
    this.mediaTimer = setInterval(function () {
		self._music.getCurrentPosition().then((curpos) => {
			self.timer = curpos;
			if ( curpos < self._music.getDuration() ) {
				this.showProgress();
			}
		});
    }, 1000);
}