apache / cordova-plugin-media

Apache Cordova Media Plugin
https://cordova.apache.org/
Apache License 2.0
390 stars 763 forks source link

Android: play & seekTo => error (-38, 0), start called in state 4 #364

Open bagilevi opened 1 year ago

bagilevi commented 1 year ago

Bug Report

Problem

Calling .play() and .seekTo() immediately one after the other causes an error on Android.

What is expected to happen?

It should start playing from the given position.

What does actually happen?

It doesn't play, and produces the following error via the error callback:

{"code":-38,"message":"AudioPlayer.onError(-38, 0)"}

This is also logged:

E/MediaPlayerNative: start called in state 4, mPlayer(0xb400007c64c690b0)
E/MediaPlayerNative: error (-38, 0)

Information

I searched for this error code, and it appears that the problem is that player.start() is called before the onPrepared callback is fired.

After digging into the implementation (AudioPlayer.java), I found that both the startPlaying and seekToPlaying call readyPlayer() and only do stuff immediately if readyPlayer() returns true, otherwise will set some values to do it in the callback once the player is ready.

readyPlayer() creates the player if it doesn't exist yet, and it looks like it is meant to return false if the player is not ready; however it seems to return true in the MEDIA_STARTING as well.

switch (this.state) {
    case MEDIA_NONE:
        if (this.player == null) {
            this.player = new MediaPlayer();
            this.player.setOnErrorListener(this);
        }
        // ...
        return false;
    case MEDIA_LOADING:
        // ...
        return false;
    case MEDIA_STARTING: // <---
    case MEDIA_RUNNING:
    case MEDIA_PAUSED:
        return true;     // <---
    case MEDIA_STOPPED:

I'm wondering if there is any reason for it to return true while MEDIA_STARTING?

Command or Code

this.media = new Media(
  src,
  successCallback,
  failureCallback,
  statusCallback,
  durationUpdateCallback
);

// The order of the following two doesn't matter
this.media.seekTo(seconds * 1000);
this.media.play();

I managed to get it working with this workaround:

if (this._mediaStatus === null || this._mediaStatus < MEDIA_RUNNING) {
  // The media is not ready yet, seek as soon as we get a MEDIA_RUNNING status
  this._seekToSecondsWhenReady = seconds;
} else {
  this.media.seekTo(seconds * 1000);
}

Environment, Platform, Device

Version information

@capacitor/android": "4.6.1",
@capacitor/assets": "2.0.4",
@capacitor/camera": "4.1.4",
@capacitor/core": "4.6.1",
@capacitor/ios": "4.6.1",
@capacitor/splash-screen": "4.1.2",
cordova-plugin-file": "7.0.0",
cordova-plugin-media": "6.1.0"

Android version: 11

Checklist