Time stretching, AndroidX, update gradle
This commit is contained in:
parent
a50daad9e1
commit
b93611dca3
208
LICENSE
208
LICENSE
|
@ -19,3 +19,211 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
==============================================================================
|
||||
|
||||
This software includes the sonic library which is licensed under the Apache
|
||||
License, Version 2.0.
|
||||
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
|
|
@ -8,7 +8,7 @@ buildscript {
|
|||
}
|
||||
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:3.2.1'
|
||||
classpath 'com.android.tools.build:gradle:3.5.0'
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -25,10 +25,16 @@ android {
|
|||
compileSdkVersion 28
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion 16
|
||||
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
|
||||
minSdkVersion 21
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
lintOptions {
|
||||
disable 'InvalidPackage'
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility 1.8
|
||||
targetCompatibility 1.8
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,2 +1,4 @@
|
|||
org.gradle.jvmargs=-Xmx1536M
|
||||
|
||||
android.enableR8=true
|
||||
android.useAndroidX=true
|
||||
android.enableJetifier=true
|
||||
|
|
|
@ -1,26 +1,35 @@
|
|||
package com.ryanheise.just_audio;
|
||||
|
||||
import android.media.MediaPlayer;
|
||||
import android.media.AudioFormat;
|
||||
import android.media.AudioManager;
|
||||
import android.media.AudioTrack;
|
||||
import android.media.MediaCodec;
|
||||
import android.media.MediaExtractor;
|
||||
import android.media.MediaFormat;
|
||||
import android.media.MediaTimestamp;
|
||||
import android.os.Handler;
|
||||
import io.flutter.plugin.common.EventChannel;
|
||||
import io.flutter.plugin.common.EventChannel.EventSink;
|
||||
import io.flutter.plugin.common.MethodCall;
|
||||
import io.flutter.plugin.common.MethodChannel;
|
||||
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
|
||||
import io.flutter.plugin.common.MethodChannel.Result;
|
||||
import java.util.List;
|
||||
import java.io.IOException;
|
||||
import android.os.Handler;
|
||||
import java.util.ArrayList;
|
||||
import io.flutter.plugin.common.PluginRegistry.Registrar;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Deque;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import sonic.Sonic;
|
||||
|
||||
public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionListener {
|
||||
public class AudioPlayer implements MethodCallHandler {
|
||||
private final Registrar registrar;
|
||||
private final MethodChannel methodChannel;
|
||||
private final EventChannel eventChannel;
|
||||
private EventSink eventSink;
|
||||
private final Handler handler = new Handler();
|
||||
private Runnable endDetector;
|
||||
private final Runnable positionObserver = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
|
@ -35,14 +44,31 @@ public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionL
|
|||
};
|
||||
|
||||
private final String id;
|
||||
private final MediaPlayer player;
|
||||
private PlaybackState state;
|
||||
private String url;
|
||||
private volatile PlaybackState state;
|
||||
private PlaybackState stateBeforeSeek;
|
||||
private long updateTime;
|
||||
private int updatePosition;
|
||||
private Integer seekPos;
|
||||
private Deque<SeekRequest> seekRequests = new LinkedList<>();
|
||||
|
||||
private MediaExtractor extractor;
|
||||
private MediaFormat format;
|
||||
private Sonic sonic;
|
||||
private int channelCount;
|
||||
private int sampleRate;
|
||||
private int duration;
|
||||
private MediaCodec codec;
|
||||
private AudioTrack audioTrack;
|
||||
private PlayThread playThread;
|
||||
private int start;
|
||||
private Integer untilPosition;
|
||||
private Object monitor = new Object();
|
||||
private float volume = 1.0f;
|
||||
private float speed = 1.0f;
|
||||
private Thread mainThread;
|
||||
|
||||
public AudioPlayer(final Registrar registrar, final String id) {
|
||||
mainThread = Thread.currentThread();
|
||||
this.registrar = registrar;
|
||||
this.id = id;
|
||||
methodChannel = new MethodChannel(registrar.messenger(), "com.ryanheise.just_audio.methods." + id);
|
||||
|
@ -60,34 +86,25 @@ public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionL
|
|||
}
|
||||
});
|
||||
state = PlaybackState.none;
|
||||
player = new MediaPlayer();
|
||||
player.setOnCompletionListener(this);
|
||||
}
|
||||
|
||||
private void checkForDiscontinuity() {
|
||||
// TODO: Consider using player.setOnMediaTimeDiscontinuityListener()
|
||||
// when available in SDK. (Added in API level 28)
|
||||
final long now = System.currentTimeMillis();
|
||||
final int position = getCurrentPosition();
|
||||
final long timeSinceLastUpdate = now - updateTime;
|
||||
final long expectedPosition = updatePosition + timeSinceLastUpdate;
|
||||
final long expectedPosition = updatePosition + (long)(timeSinceLastUpdate * speed);
|
||||
final long drift = position - expectedPosition;
|
||||
// Update if we've drifted or just started observing
|
||||
if (updateTime == 0L) {
|
||||
broadcastPlayerState();
|
||||
} else if (drift < -100) {
|
||||
System.out.println("time discontinuity detected: " + drift);
|
||||
setPlaybackState(PlaybackState.buffering);
|
||||
transition(PlaybackState.buffering);
|
||||
} else if (state == PlaybackState.buffering) {
|
||||
setPlaybackState(PlaybackState.playing);
|
||||
transition(PlaybackState.playing);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCompletion(final MediaPlayer mp) {
|
||||
setPlaybackState(PlaybackState.stopped);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMethodCall(final MethodCall call, final Result result) {
|
||||
final List<?> args = (List<?>)call.arguments;
|
||||
|
@ -105,11 +122,14 @@ public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionL
|
|||
result.success(null);
|
||||
break;
|
||||
case "stop":
|
||||
stop();
|
||||
result.success(null);
|
||||
stop(result);
|
||||
break;
|
||||
case "setVolume":
|
||||
setVolume((Double)args.get(0));
|
||||
setVolume((float)((double)((Double)args.get(0))));
|
||||
result.success(null);
|
||||
break;
|
||||
case "setSpeed":
|
||||
setSpeed((float)((double)((Double)args.get(0))));
|
||||
result.success(null);
|
||||
break;
|
||||
case "seek":
|
||||
|
@ -125,20 +145,17 @@ public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionL
|
|||
}
|
||||
} catch (IllegalStateException e) {
|
||||
e.printStackTrace();
|
||||
result.error("Illegal state", null, null);
|
||||
result.error("Illegal state: " + e.getMessage(), null, null);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
result.error("Error", null, null);
|
||||
result.error("Error: " + e, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
private void broadcastPlayerState() {
|
||||
final ArrayList<Object> event = new ArrayList<Object>();
|
||||
// state
|
||||
event.add(state.ordinal());
|
||||
// updatePosition
|
||||
event.add(updatePosition = getCurrentPosition());
|
||||
// updateTime
|
||||
event.add(updateTime = System.currentTimeMillis());
|
||||
eventSink.success(event);
|
||||
}
|
||||
|
@ -146,101 +163,243 @@ public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionL
|
|||
private int getCurrentPosition() {
|
||||
if (state == PlaybackState.none || state == PlaybackState.connecting) {
|
||||
return 0;
|
||||
} else if (seekPos != null) {
|
||||
return seekPos;
|
||||
} else if (seekRequests.size() > 0) {
|
||||
return seekRequests.peekFirst().pos;
|
||||
} else {
|
||||
return player.getCurrentPosition();
|
||||
return (int)(extractor.getSampleTime() / 1000);
|
||||
}
|
||||
}
|
||||
|
||||
private void setPlaybackState(final PlaybackState state) {
|
||||
final PlaybackState oldState = this.state;
|
||||
this.state = state;
|
||||
if (oldState != PlaybackState.playing && state == PlaybackState.playing) {
|
||||
private void transition(final PlaybackState newState) {
|
||||
transition(state, newState);
|
||||
}
|
||||
|
||||
private void transition(final PlaybackState oldState, final PlaybackState newState) {
|
||||
state = newState;
|
||||
if (oldState != PlaybackState.playing && newState == PlaybackState.playing) {
|
||||
startObservingPosition();
|
||||
}
|
||||
broadcastPlayerState();
|
||||
}
|
||||
|
||||
public void setUrl(final String url, final Result result) throws IOException {
|
||||
setPlaybackState(PlaybackState.connecting);
|
||||
player.reset();
|
||||
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
|
||||
private void bgTransition(final PlaybackState newState) {
|
||||
bgTransition(state, newState);
|
||||
}
|
||||
|
||||
private void bgTransition(final PlaybackState oldState, final PlaybackState newState) {
|
||||
// Redundant assignment which ensures the state is set
|
||||
// immediately in the background thread.
|
||||
state = newState;
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void onPrepared(final MediaPlayer mp) {
|
||||
setPlaybackState(PlaybackState.stopped);
|
||||
result.success(mp.getDuration());
|
||||
public void run() {
|
||||
transition(oldState, newState);
|
||||
}
|
||||
});
|
||||
player.setDataSource(url);
|
||||
player.prepareAsync();
|
||||
}
|
||||
|
||||
public void setUrl(final String url, final Result result) throws IOException {
|
||||
if (state != PlaybackState.none && state != PlaybackState.stopped) {
|
||||
throw new IllegalStateException("Can call setUrl only from none and stopped states");
|
||||
}
|
||||
transition(PlaybackState.connecting);
|
||||
this.url = url;
|
||||
if (extractor != null) {
|
||||
extractor.release();
|
||||
}
|
||||
new Thread(() -> {
|
||||
try {
|
||||
blockingInitExtractorAndCodec();
|
||||
|
||||
sonic = new Sonic(sampleRate, channelCount);
|
||||
sonic.setVolume(volume);
|
||||
sonic.setSpeed(speed);
|
||||
|
||||
bgTransition(PlaybackState.stopped);
|
||||
handler.post(() -> result.success(duration));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
handler.post(() -> result.error("Error: " + e, null, null));
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
public void play(final Integer untilPosition) {
|
||||
// TODO: dynamically adjust the lag.
|
||||
final int lag = 6;
|
||||
final int start = getCurrentPosition();
|
||||
if (untilPosition != null && untilPosition <= start) {
|
||||
return;
|
||||
throw new IllegalArgumentException("untilPosition must be >= 0");
|
||||
}
|
||||
player.start();
|
||||
setPlaybackState(PlaybackState.playing);
|
||||
if (endDetector != null) {
|
||||
handler.removeCallbacks(endDetector);
|
||||
this.untilPosition = untilPosition;
|
||||
switch (state) {
|
||||
case stopped:
|
||||
ensureStopped();
|
||||
transition(PlaybackState.playing);
|
||||
playThread = new PlayThread();
|
||||
playThread.start();
|
||||
break;
|
||||
case paused:
|
||||
synchronized (monitor) {
|
||||
transition(PlaybackState.playing);
|
||||
monitor.notifyAll();
|
||||
}
|
||||
if (untilPosition != null) {
|
||||
final int duration = Math.max(0, untilPosition - start - lag);
|
||||
handler.postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
final int position = getCurrentPosition();
|
||||
if (position > untilPosition - 20) {
|
||||
pause();
|
||||
} else {
|
||||
final int duration = Math.max(0, untilPosition - position - lag);
|
||||
handler.postDelayed(this, duration);
|
||||
break;
|
||||
default:
|
||||
throw new IllegalStateException("Can call play only from stopped and paused states (" + state + ")");
|
||||
}
|
||||
}
|
||||
}, duration);
|
||||
|
||||
private void ensureStopped() {
|
||||
synchronized (monitor) {
|
||||
try {
|
||||
while (playThread != null) {
|
||||
monitor.wait();
|
||||
}
|
||||
} catch (Exception e) {}
|
||||
}
|
||||
}
|
||||
|
||||
public void pause() {
|
||||
player.pause();
|
||||
setPlaybackState(PlaybackState.paused);
|
||||
switch (state) {
|
||||
case playing:
|
||||
case buffering:
|
||||
synchronized (monitor) {
|
||||
transition(PlaybackState.paused);
|
||||
audioTrack.pause();
|
||||
monitor.notifyAll();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new IllegalStateException("Can call pause only from playing and buffering states");
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
player.pause();
|
||||
player.seekTo(0);
|
||||
setPlaybackState(PlaybackState.stopped);
|
||||
public void stop(final Result result) {
|
||||
switch (state) {
|
||||
case stopped:
|
||||
break;
|
||||
// TODO: Allow stopping from buffered state.
|
||||
case playing:
|
||||
case paused:
|
||||
synchronized (monitor) {
|
||||
// It takes some time for the PlayThread to actually wind down
|
||||
// so other methods that transition from the stopped state should
|
||||
// wait for playThread == null with ensureStopped().
|
||||
PlaybackState oldState = state;
|
||||
transition(PlaybackState.stopped);
|
||||
if (oldState == PlaybackState.paused) {
|
||||
monitor.notifyAll();
|
||||
} else {
|
||||
audioTrack.pause();
|
||||
}
|
||||
new Thread(() -> {
|
||||
ensureStopped();
|
||||
handler.post(() -> result.success(null));
|
||||
}).start();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new IllegalStateException("Can call stop only from playing, paused and buffering states");
|
||||
}
|
||||
}
|
||||
|
||||
public void setVolume(final double volume) {
|
||||
player.setVolume((float)volume, (float)volume);
|
||||
public void setVolume(final float volume) {
|
||||
this.volume = volume;
|
||||
if (sonic != null) {
|
||||
sonic.setVolume(volume);
|
||||
}
|
||||
}
|
||||
|
||||
public void setSpeed(final float speed) {
|
||||
// NOTE: existing audio data in the pipeline will continue
|
||||
// to play out at the speed it was already processed at. So
|
||||
// for a brief moment, checkForDiscontinuity() may erroneously
|
||||
// detect some buffering.
|
||||
// TODO: Sort this out. The cheap workaround would be to disable
|
||||
// checks for discontinuity during this brief moment.
|
||||
this.speed = speed;
|
||||
if (sonic != null) {
|
||||
sonic.setSpeed(speed);
|
||||
}
|
||||
broadcastPlayerState();
|
||||
}
|
||||
|
||||
// TODO: Test whether this times out the MediaCodec on Ogg files.
|
||||
// See: https://stackoverflow.com/questions/22109050/mediacodec-dequeueoutputbuffer-times-out-when-seeking-with-ogg-audio-files
|
||||
public void seek(final int position, final Result result) {
|
||||
stateBeforeSeek = state;
|
||||
seekPos = position;
|
||||
handler.removeCallbacks(positionObserver);
|
||||
setPlaybackState(PlaybackState.buffering);
|
||||
player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
|
||||
@Override
|
||||
public void onSeekComplete(final MediaPlayer mp) {
|
||||
seekPos = null;
|
||||
setPlaybackState(stateBeforeSeek);
|
||||
stateBeforeSeek = null;
|
||||
result.success(null);
|
||||
player.setOnSeekCompleteListener(null);
|
||||
synchronized (monitor) {
|
||||
if (state == PlaybackState.none || state == PlaybackState.connecting) {
|
||||
throw new IllegalStateException("Cannot call seek in none or connecting states");
|
||||
}
|
||||
if (state == PlaybackState.stopped) {
|
||||
ensureStopped();
|
||||
}
|
||||
start = position;
|
||||
if (seekRequests.size() == 0) {
|
||||
stateBeforeSeek = state;
|
||||
}
|
||||
seekRequests.addLast(new SeekRequest(position, result));
|
||||
handler.removeCallbacks(positionObserver);
|
||||
transition(PlaybackState.buffering);
|
||||
if (stateBeforeSeek == PlaybackState.stopped) {
|
||||
new Thread(() -> {
|
||||
processSeekRequests();
|
||||
}).start();
|
||||
} else {
|
||||
monitor.notifyAll();
|
||||
}
|
||||
}
|
||||
});
|
||||
player.seekTo(position);
|
||||
}
|
||||
|
||||
public void dispose() {
|
||||
player.release();
|
||||
setPlaybackState(PlaybackState.none);
|
||||
if (state != PlaybackState.stopped && state != PlaybackState.none) {
|
||||
throw new IllegalStateException("Can call dispose only from stopped and none states");
|
||||
}
|
||||
if (extractor != null) {
|
||||
ensureStopped();
|
||||
transition(PlaybackState.none);
|
||||
extractor.release();
|
||||
extractor = null;
|
||||
codec.stop();
|
||||
codec.release();
|
||||
codec = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void blockingInitExtractorAndCodec() throws IOException {
|
||||
extractor = new MediaExtractor();
|
||||
extractor.setDataSource(url);
|
||||
format = selectAudioTrack(extractor);
|
||||
channelCount = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
|
||||
sampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
|
||||
long durationMs = format.getLong(MediaFormat.KEY_DURATION);
|
||||
duration = (int)(durationMs / 1000);
|
||||
start = 0;
|
||||
codec = MediaCodec.createDecoderByType(format.getString(MediaFormat.KEY_MIME));
|
||||
codec.configure(format, null, null, 0);
|
||||
codec.start();
|
||||
}
|
||||
|
||||
private MediaFormat selectAudioTrack(MediaExtractor extractor) throws IOException {
|
||||
int trackCount = extractor.getTrackCount();
|
||||
for (int i = 0; i < trackCount; i++) {
|
||||
MediaFormat format = extractor.getTrackFormat(i);
|
||||
if (format.getString(MediaFormat.KEY_MIME).startsWith("audio/")) {
|
||||
extractor.selectTrack(i);
|
||||
return format;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No audio track found");
|
||||
}
|
||||
|
||||
private void processSeekRequests() {
|
||||
while (seekRequests.size() > 0) {
|
||||
SeekRequest seekRequest = seekRequests.removeFirst();
|
||||
extractor.seekTo(seekRequest.pos*1000L, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
|
||||
if (seekRequests.size() == 0) {
|
||||
bgTransition(stateBeforeSeek);
|
||||
stateBeforeSeek = null;
|
||||
}
|
||||
handler.post(() -> seekRequest.result.success(null));
|
||||
}
|
||||
}
|
||||
|
||||
private void startObservingPosition() {
|
||||
|
@ -248,6 +407,217 @@ public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionL
|
|||
handler.post(positionObserver);
|
||||
}
|
||||
|
||||
private class PlayThread extends Thread {
|
||||
private static final int TIMEOUT = 1000;
|
||||
private static final int FRAME_SIZE = 1024*2;
|
||||
private static final int BEHIND_LIMIT = 500; // ms
|
||||
private byte[] silence;
|
||||
private boolean finishedDecoding = false;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
int encoding = AudioFormat.ENCODING_PCM_16BIT;
|
||||
int channelFormat = channelCount==1?AudioFormat.CHANNEL_OUT_MONO:AudioFormat.CHANNEL_OUT_STEREO;
|
||||
int minSize = AudioTrack.getMinBufferSize(sampleRate, channelFormat, encoding);
|
||||
int audioTrackBufferSize = minSize * 4;
|
||||
audioTrack = new AudioTrack(
|
||||
AudioManager.STREAM_MUSIC,
|
||||
sampleRate,
|
||||
channelFormat,
|
||||
encoding,
|
||||
audioTrackBufferSize,
|
||||
AudioTrack.MODE_STREAM);
|
||||
|
||||
silence = new byte[audioTrackBufferSize];
|
||||
|
||||
MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
|
||||
boolean firstSample = true;
|
||||
int decoderIdleCount = 0;
|
||||
boolean finishedReading = false;
|
||||
int progress = 0;
|
||||
// The extractor position seems to jump around at the beginning.
|
||||
// This is a hack to address that.
|
||||
long behindStartTime = 0;
|
||||
byte[] sonicOut = new byte[audioTrackBufferSize];
|
||||
try {
|
||||
audioTrack.play();
|
||||
while (!finishedDecoding) {
|
||||
|
||||
if (checkForRequest()) continue;
|
||||
|
||||
// put data into input buffer
|
||||
|
||||
if (!finishedReading) {
|
||||
int inputBufferIndex = codec.dequeueInputBuffer(TIMEOUT);
|
||||
if (inputBufferIndex >= 0) {
|
||||
ByteBuffer inputBuffer = codec.getInputBuffer(inputBufferIndex);
|
||||
long presentationTime = extractor.getSampleTime();
|
||||
int presentationTimeMs = (int)(presentationTime / 1000);
|
||||
if (presentationTimeMs < start) {
|
||||
if (behindStartTime == 0) behindStartTime = System.currentTimeMillis();
|
||||
if (System.currentTimeMillis() - behindStartTime > BEHIND_LIMIT) {
|
||||
System.out.println("Too early, re-seeking");
|
||||
extractor.seekTo(start*1000L, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
|
||||
behindStartTime = 0;
|
||||
}
|
||||
} else {
|
||||
behindStartTime = 0;
|
||||
}
|
||||
int sampleSize = extractor.readSampleData(inputBuffer, 0);
|
||||
if (firstSample && sampleSize == 2 && format.getString(MediaFormat.KEY_MIME).equals("audio/mp4a-latm")) {
|
||||
// Skip initial frames.
|
||||
extractor.advance();
|
||||
} else if (sampleSize >= 0) {
|
||||
codec.queueInputBuffer(inputBufferIndex, 0, sampleSize, presentationTime, 0);
|
||||
extractor.advance();
|
||||
} else {
|
||||
codec.queueInputBuffer(inputBufferIndex, 0, 0, -1, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
|
||||
finishedReading = true;
|
||||
}
|
||||
firstSample = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (checkForRequest()) continue;
|
||||
|
||||
// read data from output buffer
|
||||
|
||||
int outputBufferIndex = codec.dequeueOutputBuffer(info, TIMEOUT);
|
||||
decoderIdleCount++;
|
||||
if (outputBufferIndex >= 0) {
|
||||
int currentPosition = (int)(info.presentationTimeUs/1000);
|
||||
ByteBuffer buf = codec.getOutputBuffer(outputBufferIndex);
|
||||
if (info.size > 0) {
|
||||
decoderIdleCount = 0;
|
||||
|
||||
final byte[] chunk = new byte[info.size];
|
||||
buf.get(chunk);
|
||||
buf.clear();
|
||||
|
||||
// put decoded data into sonic
|
||||
|
||||
if (chunk.length > 0) {
|
||||
sonic.writeBytesToStream(chunk, chunk.length);
|
||||
} else {
|
||||
sonic.flushStream();
|
||||
}
|
||||
|
||||
// output sonic'd data to audioTrack
|
||||
|
||||
int numWritten;
|
||||
do {
|
||||
numWritten = sonic.readBytesFromStream(sonicOut, sonicOut.length);
|
||||
if (numWritten > 0) {
|
||||
audioTrack.write(sonicOut, 0, numWritten);
|
||||
}
|
||||
} while (numWritten > 0);
|
||||
}
|
||||
|
||||
// Detect end of playback
|
||||
|
||||
codec.releaseOutputBuffer(outputBufferIndex, false);
|
||||
if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
|
||||
if (untilPosition != null) {
|
||||
extractor.release();
|
||||
codec.flush();
|
||||
codec.stop();
|
||||
codec.release();
|
||||
blockingInitExtractorAndCodec();
|
||||
finishedReading = false;
|
||||
finishedDecoding = false;
|
||||
decoderIdleCount = 0;
|
||||
audioTrack.pause();
|
||||
bgTransition(PlaybackState.paused);
|
||||
} else {
|
||||
audioTrack.pause();
|
||||
finishedDecoding = true;
|
||||
}
|
||||
} else if (untilPosition != null && currentPosition >= untilPosition) {
|
||||
// NOTE: When streaming audio over bluetooth, it clips off
|
||||
// the last 200-300ms of the clip, even though it has been
|
||||
// written to the AudioTrack. So, we need an option to pad the
|
||||
// audio with an extra 200-300ms of silence.
|
||||
// Could be a good idea to do the same at the start
|
||||
// since some bluetooth headphones fade in and miss the
|
||||
// first little bit.
|
||||
|
||||
Arrays.fill(sonicOut, (byte)0);
|
||||
audioTrack.write(sonicOut, 0, sonicOut.length);
|
||||
bgTransition(PlaybackState.paused);
|
||||
audioTrack.pause();
|
||||
}
|
||||
} else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
|
||||
// Don't expect this to happen in audio files, but could be wrong.
|
||||
// TODO: Investigate.
|
||||
//MediaFormat newFormat = codec.getOutputFormat();
|
||||
}
|
||||
if (decoderIdleCount >= 100) {
|
||||
// Data has stopped coming through the pipeline despite not receiving a
|
||||
// BUFFER_FLAG_END_OF_STREAM signal, so stop.
|
||||
System.out.println("decoderIdleCount >= 100. finishedDecoding = true");
|
||||
finishedDecoding = true;
|
||||
audioTrack.pause();
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
codec.flush();
|
||||
audioTrack.flush();
|
||||
audioTrack.release();
|
||||
audioTrack = null;
|
||||
synchronized (monitor) {
|
||||
start = 0;
|
||||
untilPosition = null;
|
||||
bgTransition(PlaybackState.stopped);
|
||||
extractor.seekTo(0L, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
|
||||
playThread = null;
|
||||
monitor.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Return true to "continue" to the audio loop
|
||||
private boolean checkForRequest() {
|
||||
try {
|
||||
synchronized (monitor) {
|
||||
if (state == PlaybackState.paused) {
|
||||
while (state == PlaybackState.paused) {
|
||||
monitor.wait();
|
||||
}
|
||||
// Unpaused
|
||||
// Reset updateTime for higher accuracy.
|
||||
bgTransition(state);
|
||||
if (state == PlaybackState.playing) {
|
||||
audioTrack.play();
|
||||
} else if (state == PlaybackState.buffering) {
|
||||
// TODO: What if we are in the second checkForRequest call and
|
||||
// we ask to continue the loop, we may forget about dequeued
|
||||
// input buffers. Need to handle this correctly.
|
||||
return true;
|
||||
}
|
||||
} else if (state == PlaybackState.buffering && seekRequests.size() > 0) {
|
||||
// Seek requested
|
||||
codec.flush();
|
||||
audioTrack.flush();
|
||||
processSeekRequests();
|
||||
if (state != PlaybackState.stopped) {
|
||||
// The == stopped case is handled below.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (state == PlaybackState.stopped) {
|
||||
finishedDecoding = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e) {}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
enum PlaybackState {
|
||||
none,
|
||||
stopped,
|
||||
|
@ -256,4 +626,14 @@ public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionL
|
|||
buffering,
|
||||
connecting
|
||||
}
|
||||
|
||||
class SeekRequest {
|
||||
public final int pos;
|
||||
public final Result result;
|
||||
|
||||
public SeekRequest(int pos, Result result) {
|
||||
this.pos = pos;
|
||||
this.result = result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,6 +5,7 @@ import io.flutter.plugin.common.MethodChannel;
|
|||
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
|
||||
import io.flutter.plugin.common.MethodChannel.Result;
|
||||
import io.flutter.plugin.common.PluginRegistry.Registrar;
|
||||
import java.util.List;
|
||||
|
||||
/** JustAudioPlugin */
|
||||
public class JustAudioPlugin implements MethodCallHandler {
|
||||
|
@ -24,7 +25,8 @@ public class JustAudioPlugin implements MethodCallHandler {
|
|||
public void onMethodCall(MethodCall call, Result result) {
|
||||
switch (call.method) {
|
||||
case "init":
|
||||
String id = (String)call.arguments;
|
||||
final List<?> args = (List<?>)call.arguments;
|
||||
String id = (String)args.get(0);
|
||||
new AudioPlayer(registrar, id);
|
||||
result.success(null);
|
||||
break;
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -24,6 +24,7 @@
|
|||
**/doc/api/
|
||||
.dart_tool/
|
||||
.flutter-plugins
|
||||
.flutter-plugins-dependencies
|
||||
.packages
|
||||
.pub-cache/
|
||||
.pub/
|
||||
|
|
|
@ -34,11 +34,11 @@ android {
|
|||
defaultConfig {
|
||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||
applicationId "com.ryanheise.just_audio_example"
|
||||
minSdkVersion 16
|
||||
minSdkVersion 21
|
||||
targetSdkVersion 28
|
||||
versionCode flutterVersionCode.toInteger()
|
||||
versionName flutterVersionName
|
||||
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
|
@ -56,6 +56,6 @@ flutter {
|
|||
|
||||
dependencies {
|
||||
testImplementation 'junit:junit:4.12'
|
||||
androidTestImplementation 'com.android.support.test:runner:1.0.2'
|
||||
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
|
||||
androidTestImplementation 'androidx.test:runner:1.1.1'
|
||||
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
|
||||
}
|
||||
|
|
|
@ -5,7 +5,7 @@ buildscript {
|
|||
}
|
||||
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:3.2.1'
|
||||
classpath 'com.android.tools.build:gradle:3.5.0'
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,2 +1,4 @@
|
|||
org.gradle.jvmargs=-Xmx1536M
|
||||
|
||||
android.enableR8=true
|
||||
android.useAndroidX=true
|
||||
android.enableJetifier=true
|
||||
|
|
|
@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
|
|||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
|
||||
|
|
|
@ -1,10 +1,7 @@
|
|||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
import 'package:rxdart/rxdart.dart';
|
||||
|
||||
void main() => runApp(MyApp());
|
||||
|
||||
|
@ -14,11 +11,14 @@ class MyApp extends StatefulWidget {
|
|||
}
|
||||
|
||||
class _MyAppState extends State<MyApp> {
|
||||
final AudioPlayer _player = AudioPlayer();
|
||||
final _volumeSubject = BehaviorSubject.seeded(1.0);
|
||||
final _speedSubject = BehaviorSubject.seeded(1.0);
|
||||
AudioPlayer _player;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_player = AudioPlayer();
|
||||
_player.setUrl(
|
||||
"https://s3.amazonaws.com/scifri-episodes/scifri20181123-episode.mp3");
|
||||
}
|
||||
|
@ -82,6 +82,7 @@ class _MyAppState extends State<MyApp> {
|
|||
);
|
||||
},
|
||||
),
|
||||
Text("Track position"),
|
||||
StreamBuilder<Duration>(
|
||||
stream: _player.durationStream,
|
||||
builder: (context, snapshot) {
|
||||
|
@ -101,6 +102,34 @@ class _MyAppState extends State<MyApp> {
|
|||
);
|
||||
},
|
||||
),
|
||||
Text("Volume"),
|
||||
StreamBuilder<double>(
|
||||
stream: _volumeSubject.stream,
|
||||
builder: (context, snapshot) => Slider(
|
||||
divisions: 20,
|
||||
min: 0.0,
|
||||
max: 2.0,
|
||||
value: snapshot.data ?? 1.0,
|
||||
onChanged: (value) {
|
||||
_volumeSubject.add(value);
|
||||
_player.setVolume(value);
|
||||
},
|
||||
),
|
||||
),
|
||||
Text("Speed"),
|
||||
StreamBuilder<double>(
|
||||
stream: _speedSubject.stream,
|
||||
builder: (context, snapshot) => Slider(
|
||||
divisions: 10,
|
||||
min: 0.5,
|
||||
max: 1.5,
|
||||
value: snapshot.data ?? 1.0,
|
||||
onChanged: (value) {
|
||||
_speedSubject.add(value);
|
||||
_player.setSpeed(value);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
|
|
@ -7,7 +7,7 @@ packages:
|
|||
name: archive
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.0.10"
|
||||
version: "2.0.11"
|
||||
args:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
@ -21,7 +21,7 @@ packages:
|
|||
name: async
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.3.0"
|
||||
version: "2.4.0"
|
||||
boolean_selector:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
@ -87,21 +87,21 @@ packages:
|
|||
path: ".."
|
||||
relative: true
|
||||
source: path
|
||||
version: "0.0.1"
|
||||
version: "0.0.2"
|
||||
matcher:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: matcher
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "0.12.5"
|
||||
version: "0.12.6"
|
||||
meta:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: meta
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "1.1.7"
|
||||
version: "1.1.8"
|
||||
path:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
@ -145,12 +145,12 @@ packages:
|
|||
source: hosted
|
||||
version: "2.0.5"
|
||||
rxdart:
|
||||
dependency: transitive
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: rxdart
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "0.22.6"
|
||||
version: "0.23.1"
|
||||
sky_engine:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
|
@ -197,7 +197,7 @@ packages:
|
|||
name: test_api
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "0.2.5"
|
||||
version: "0.2.11"
|
||||
typed_data:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
@ -220,5 +220,5 @@ packages:
|
|||
source: hosted
|
||||
version: "3.5.0"
|
||||
sdks:
|
||||
dart: ">=2.4.0 <3.0.0"
|
||||
dart: ">=2.6.0 <3.0.0"
|
||||
flutter: ">=1.9.1+hotfix.5 <2.0.0"
|
||||
|
|
|
@ -6,9 +6,8 @@ dependencies:
|
|||
flutter:
|
||||
sdk: flutter
|
||||
|
||||
# The following adds the Cupertino Icons font to your application.
|
||||
# Use with the CupertinoIcons class for iOS style icons.
|
||||
cupertino_icons: ^0.1.2
|
||||
rxdart: ^0.23.1
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
|
|
@ -60,6 +60,9 @@
|
|||
} else if ([@"setVolume" isEqualToString:call.method]) {
|
||||
[self setVolume:(float)[args[0] doubleValue]];
|
||||
result(nil);
|
||||
} else if ([@"setSpeed" isEqualToString:call.method]) {
|
||||
[self setSpeed:(float)[args[0] doubleValue]];
|
||||
result(nil);
|
||||
} else if ([@"seek" isEqualToString:call.method]) {
|
||||
[self seek:[args[0] intValue] result:result];
|
||||
result(nil);
|
||||
|
@ -92,7 +95,7 @@
|
|||
long long now = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0);
|
||||
int position = [self getCurrentPosition];
|
||||
long long timeSinceLastUpdate = now - _updateTime;
|
||||
long long expectedPosition = _updatePosition + timeSinceLastUpdate;
|
||||
long long expectedPosition = _updatePosition + timeSinceLastUpdate; // TODO: * speed
|
||||
long long drift = position - expectedPosition;
|
||||
// Update if we've drifted or just started observing
|
||||
if (_updateTime == 0L) {
|
||||
|
@ -257,6 +260,14 @@
|
|||
[_player setVolume:volume];
|
||||
}
|
||||
|
||||
- (void)setSpeed:(float)speed {
|
||||
//if (speed == 1.0
|
||||
// || speed < 1.0 && _player.currentItem.canPlaySlowForward
|
||||
// || speed > 1.0 && _player.currentItem.canPlayFastForward) {
|
||||
// _player.rate = speed;
|
||||
//}
|
||||
}
|
||||
|
||||
- (void)seek:(int)position result:(FlutterResult)result {
|
||||
_stateBeforeSeek = _state;
|
||||
_seekPos = position;
|
||||
|
|
|
@ -23,7 +23,8 @@
|
|||
|
||||
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
|
||||
if ([@"init" isEqualToString:call.method]) {
|
||||
NSString* playerId = call.arguments;
|
||||
NSArray* args = (NSArray*)call.arguments;
|
||||
NSString* playerId = args[0];
|
||||
AudioPlayer* player = [[AudioPlayer alloc] initWithRegistrar:_registrar playerId:playerId];
|
||||
result(nil);
|
||||
} else {
|
||||
|
|
|
@ -46,8 +46,8 @@ import 'package:rxdart/rxdart.dart';
|
|||
class AudioPlayer {
|
||||
static final _mainChannel = MethodChannel('com.ryanheise.just_audio.methods');
|
||||
|
||||
static Future<MethodChannel> _createChannel(int id) async {
|
||||
await _mainChannel.invokeMethod('init', '$id');
|
||||
static Future<MethodChannel> _init(int id) async {
|
||||
await _mainChannel.invokeMethod('init', ['$id']);
|
||||
return MethodChannel('com.ryanheise.just_audio.methods.$id');
|
||||
}
|
||||
|
||||
|
@ -69,22 +69,31 @@ class AudioPlayer {
|
|||
|
||||
final _playbackStateSubject = BehaviorSubject<AudioPlaybackState>();
|
||||
|
||||
double _volume = 1.0;
|
||||
|
||||
double _speed = 1.0;
|
||||
|
||||
/// Creates an [AudioPlayer].
|
||||
factory AudioPlayer() =>
|
||||
AudioPlayer._internal(DateTime.now().microsecondsSinceEpoch);
|
||||
|
||||
AudioPlayer._internal(this._id) : _channel = _createChannel(_id) {
|
||||
AudioPlayer._internal(this._id) : _channel = _init(_id) {
|
||||
_eventChannelStream = EventChannel('com.ryanheise.just_audio.events.$_id')
|
||||
.receiveBroadcastStream()
|
||||
.map((data) => _audioPlayerState = AudioPlayerState(
|
||||
state: AudioPlaybackState.values[data[0]],
|
||||
updatePosition: Duration(milliseconds: data[1]),
|
||||
updateTime: Duration(milliseconds: data[2]),
|
||||
speed: _speed,
|
||||
));
|
||||
_eventChannelStreamSubscription =
|
||||
_eventChannelStream.listen(_playerStateSubject.add);
|
||||
_playbackStateSubject
|
||||
.addStream(playerStateStream.map((state) => state.state).distinct());
|
||||
|
||||
playerStateStream.listen((state) {
|
||||
print("state: $state");
|
||||
});
|
||||
}
|
||||
|
||||
/// The duration of any media set via [setUrl], [setFilePath] or [setAsset],
|
||||
|
@ -107,11 +116,18 @@ class AudioPlayer {
|
|||
/// A stream periodically tracking the current position of this player.
|
||||
Stream<Duration> getPositionStream(
|
||||
[final Duration period = const Duration(milliseconds: 200)]) =>
|
||||
Observable.combineLatest2<AudioPlayerState, void, Duration>(
|
||||
Rx.combineLatest2<AudioPlayerState, void, Duration>(
|
||||
playerStateStream,
|
||||
Observable.periodic(period),
|
||||
// TODO: emit periodically only in playing state.
|
||||
Stream.periodic(period),
|
||||
(state, _) => state.position);
|
||||
|
||||
/// The current volume of the player.
|
||||
double get volume => _volume;
|
||||
|
||||
/// The current speed of the player.
|
||||
double get speed => _speed;
|
||||
|
||||
/// Loads audio media from a URL and returns the duration of that audio.
|
||||
Future<Duration> setUrl(final String url) async {
|
||||
_durationFuture =
|
||||
|
@ -170,10 +186,11 @@ class AudioPlayer {
|
|||
}
|
||||
|
||||
/// Stops the currently playing media such that the next [play] invocation
|
||||
/// will start from position 0. It is legal to invoke this method from any
|
||||
/// state except for:
|
||||
/// will start from position 0. It is legal to invoke this method only from
|
||||
/// the following states:
|
||||
///
|
||||
/// * [AudioPlaybackState.none]
|
||||
/// * [AudioPlaybackState.playing]
|
||||
/// * [AudioPlaybackState.paused]
|
||||
/// * [AudioPlaybackState.stopped]
|
||||
Future<void> stop() async {
|
||||
await _invokeMethod('stop');
|
||||
|
@ -181,9 +198,16 @@ class AudioPlayer {
|
|||
|
||||
/// Sets the volume of this player, where 1.0 is normal volume.
|
||||
Future<void> setVolume(final double volume) async {
|
||||
_volume = volume;
|
||||
await _invokeMethod('setVolume', [volume]);
|
||||
}
|
||||
|
||||
/// Sets the playback speed of this player, where 1.0 is normal speed.
|
||||
Future<void> setSpeed(final double speed) async {
|
||||
_speed = speed;
|
||||
await _invokeMethod('setSpeed', [speed]);
|
||||
}
|
||||
|
||||
/// Seeks to a particular position. It is legal to invoke this method
|
||||
/// from any state except for [AudioPlaybackState.none].
|
||||
Future<void> seek(final Duration position) async {
|
||||
|
@ -218,18 +242,26 @@ class AudioPlayerState {
|
|||
/// The position at [updateTime].
|
||||
final Duration updatePosition;
|
||||
|
||||
/// The playback speed.
|
||||
final double speed;
|
||||
|
||||
AudioPlayerState({
|
||||
@required this.state,
|
||||
@required this.updateTime,
|
||||
@required this.updatePosition,
|
||||
@required this.speed,
|
||||
});
|
||||
|
||||
/// The current position of the player.
|
||||
Duration get position => state == AudioPlaybackState.playing
|
||||
? updatePosition +
|
||||
(Duration(milliseconds: DateTime.now().millisecondsSinceEpoch) -
|
||||
updateTime)
|
||||
updateTime) *
|
||||
speed
|
||||
: updatePosition;
|
||||
|
||||
@override
|
||||
String toString() => "{state=$state, updateTime=$updateTime, updatePosition=$updatePosition, speed=$speed}";
|
||||
}
|
||||
|
||||
/// Enumerates the different playback states of a player.
|
||||
|
|
61
pubspec.lock
61
pubspec.lock
|
@ -1,13 +1,27 @@
|
|||
# Generated by pub
|
||||
# See https://dart.dev/tools/pub/glossary#lockfile
|
||||
packages:
|
||||
archive:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: archive
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.0.11"
|
||||
args:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: args
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "1.5.2"
|
||||
async:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: async
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.3.0"
|
||||
version: "2.4.0"
|
||||
boolean_selector:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
@ -29,6 +43,20 @@ packages:
|
|||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "1.14.11"
|
||||
convert:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: convert
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.1.1"
|
||||
crypto:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: crypto
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.1.3"
|
||||
flutter:
|
||||
dependency: "direct main"
|
||||
description: flutter
|
||||
|
@ -39,20 +67,27 @@ packages:
|
|||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
image:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: image
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.1.4"
|
||||
matcher:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: matcher
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "0.12.5"
|
||||
version: "0.12.6"
|
||||
meta:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: meta
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "1.1.7"
|
||||
version: "1.1.8"
|
||||
path:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
|
@ -74,6 +109,13 @@ packages:
|
|||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "1.8.0+1"
|
||||
petitparser:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: petitparser
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.4.0"
|
||||
platform:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
@ -94,7 +136,7 @@ packages:
|
|||
name: rxdart
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "0.22.6"
|
||||
version: "0.23.1"
|
||||
sky_engine:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
|
@ -141,7 +183,7 @@ packages:
|
|||
name: test_api
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "0.2.5"
|
||||
version: "0.2.11"
|
||||
typed_data:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
@ -156,6 +198,13 @@ packages:
|
|||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.0.8"
|
||||
xml:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: xml
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "3.5.0"
|
||||
sdks:
|
||||
dart: ">=2.2.2 <3.0.0"
|
||||
dart: ">=2.6.0 <3.0.0"
|
||||
flutter: ">=1.9.1+hotfix.5 <2.0.0"
|
||||
|
|
|
@ -8,7 +8,7 @@ environment:
|
|||
sdk: ">=2.1.0 <3.0.0"
|
||||
|
||||
dependencies:
|
||||
rxdart: ^0.22.6
|
||||
rxdart: ^0.23.1
|
||||
path: ^1.6.4
|
||||
path_provider: ^1.4.5
|
||||
flutter:
|
||||
|
|
Loading…
Reference in New Issue