Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Elapsed time is not updating #30

Open
jlopez0313 opened this issue Nov 28, 2024 · 4 comments
Open

Elapsed time is not updating #30

jlopez0313 opened this issue Nov 28, 2024 · 4 comments

Comments

@jlopez0313
Copy link

jlopez0313 commented Nov 28, 2024

Hi there,

All works fine, only got a problem,.. Neither elapsed time nor duration are changing in the modal window on Android, this is my code:
image


let durationTime = 0;
let elapsedTime = 0;
let intervalId = null;
let isPlaying = true;

export const create = (baseURL, audio, onPlay, onPause, onGoBack, onGoNext) => {
  // destroy();

  const music = new Audio(baseURL + audio.audio);
  music.addEventListener("loadedmetadata", () => {
    durationTime = music.duration;

    CapacitorMusicControls.create({
      track: audio.titulo, // optional, default : ''
      artist: "Mente360", // optional, default : ''
      album: audio.categoria.categoria, // optional, default: ''
      cover: baseURL + audio.imagen, // optional, default : nothing

      // hide previous/next/close buttons:
      hasPrev: true, // show previous button, optional, default: true
      hasNext: true, // show next button, optional, default: true
      hasClose: true, // show close button, optional, default: false

      // iOS only, all optional
      duration: durationTime, // default: 0
      elapsed: elapsedTime, // default: 0
      hasSkipForward: true, // default: false. true value overrides hasNext.
      hasSkipBackward: true, // default: false. true value overrides hasPrev.
      skipForwardInterval: 15, // default: 15.
      skipBackwardInterval: 15, // default: 15.
      hasScrubbing: false, // default: false. Enable scrubbing from control center progress bar

      // Android only, all optional
      isPlaying: isPlaying, // default : true
      dismissable: false, // default : false
      // text displayed in the status bar when the notification (and the ticker) are updated
      ticker: audio.titulo,
      // All icons default to their built-in android equivalents
      // The supplied drawable name, e.g. 'media_play', is the name of a drawable found under android/res/drawable* folders
      playIcon: "media_play",
      pauseIcon: "media_pause",
      prevIcon: "media_prev",
      nextIcon: "media_next",
      closeIcon: "media_close",
      notificationIcon: "notification",
    })
      .then(() => {
        console.log("created");

        intervalId = setInterval(() => {
          if ( isPlaying ) {
            elapsedTime++;
            CapacitorMusicControls.updateElapsed({
              elapsed: elapsedTime,
              isPlaying: isPlaying,
            });
          }
        }, 1000);

        CapacitorMusicControls.addListener("controlsNotification", (action) => {
          console.log("controlsNotification was fired", action);
          handleControlsEvent(action, onPlay, onPause, onGoBack, onGoNext);
        });

        document.addEventListener("controlsNotification", (event) => {
          console.log("controlsNotification was fired", event);
          const info = { message: event.message, position: 0 };
          handleControlsEvent(info, onPlay, onPause, onGoBack, onGoNext);
        });
      })
      .catch((e) => {
        console.error(e);
      });
  });
};

export const toggle = (_isPlaying = true) => {
  isPlaying = _isPlaying;
  CapacitorMusicControls.updateIsPlaying({ isPlaying: _isPlaying }); // toggle the play/pause notification button
  // CapacitorMusicControls.updateDismissable(isPlaying ? false : true);
};

export const handleControlsEvent = (
  action,
  onPlay = () => {},
  onPause = () => {},
  onGoBack = () => {},
  onGoNext = () => {}
) => {
  console.log("hello from handleControlsEvent", action);
  const message = action.message;

  switch (message) {
    case "music-controls-next":
      toggle(true);
      onGoNext();
      console.log(" music-controls-next ");
      break;
    case "music-controls-previous":
      toggle(true);
      onGoBack();
      console.log(" music-controls-previous ");
      break;
    case "music-controls-pause":
      console.log(" music-controls-pause ");
      toggle(false);
      onPause();
      break;
    case "music-controls-play":
      toggle(true);
      onPlay();
      console.log(" music-controls-play ");
      break;
    case "music-controls-destroy":
      console.log(" music-controls-destroy ");
      break;

    // External controls (iOS only)
    case "music-controls-toggle-play-pause":
      // do something
      console.log(" music-controls-toggle-play-pause ");
      break;
    case "music-controls-skip-to":
      // do something
      console.log(" music-controls-skip-to ");
      break;
    case "music-controls-skip-forward":
      // Do something
      break;
    case "music-controls-skip-backward":
      // Do something
      console.log(" music-controls-skip-backward ");
      break;

    // Headset events (Android only)
    // All media button events are listed below
    case "music-controls-media-button":
      // Do something
      break;
    case "music-controls-headset-unplugged":
      // Do something
      console.log(" music-controls-headset-unplugged");
      break;
    case "music-controls-headset-plugged":
      // Do something
      console.log(" music-controls-headset-plugged ");
      break;
    default:
      break;
  }
};

export const destroy = () => {
  if (intervalId) {
    clearInterval(intervalId);
  }
  CapacitorMusicControls.destroy();
};

@leochangliao
Copy link

leochangliao commented Dec 31, 2024

share_3513334872351339985

I was playing around with the plugin source code, and got elapsed time work. I think owner of this plugin should be able to fix it. Here is portion of code that I modified:

**create():**
need to give duration:
metadataBuilder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION,infos.duration);

**setMediaPlaybackState():**
need to add
PlaybackStateCompat.ACTION_SEEK_TO

and update position:
play
playbackstateBuilder.setState(state, elapsed, 1.0f);

pause
playbackstateBuilder.setState(state, elapsed, 0);

**MediaSessionCallback:**
add onSeekTo event
public void onSeekTo(long pos)

Please note that, duration and elapsed time need to be in ms not seconds. Media plugin return duration and elapsed time in seconds btw.

@jlopez0313
Copy link
Author

@leochangliao Is it possible for you to share the complete code of both files you modified?
Also, thanks a lot for taking time to help fix it.

@leochangliao
Copy link

leochangliao commented Dec 31, 2024

@leochangliao Is it possible for you to share the complete code of both files you modified? Also, thanks a lot for taking time to help fix it.

I would suggest wait for owner's update, but here you go, hope I didn't miss any thing.

android.zip

replace android portion of this plugin at:
.../node_modules/capacitor-music-controls-plugin /android/src/main/java/com/ingageco/capacitormusiccontrols/

now you can change and get position in:

     document.addEventListener("controlsNotification", (event:any)  => { ... }
     const info = { message: event.message, position: 0 };
     to
     const info = { message: event.message, position: event.position||0 };

Update both duration and elapsed when create, play and pause. No need to update position every second as some
suggested.
(note: duration is needed when create, otherwise it won't show time elapsed bar)

     CapacitorMusicControls.create({
        ...
         // iOS only, all optional (Android too, not optional)
        duration: duration||1, // Android use ms, iOS take seconds
        elapsed: 0, // default: 0
        ...
    })
    CapacitorMusicControls.updateElapsed({
      elapsed: elapsed // Android use ms, iOS take seconds
      isPlaying: true // or false
    });

@ingageco
Copy link
Owner

ingageco commented Jan 6, 2025

@jlopez0313 @leochangliao Thank you both for the feedback/update - somehow this flew under my radar until now. I will get this updated when my schedule clears in the next week or so.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants