Time stretching, AndroidX, update gradle

This commit is contained in:
Ryan Heise 2019-12-26 00:44:08 +11:00
parent a50daad9e1
commit b93611dca3
19 changed files with 1963 additions and 160 deletions

208
LICENSE
View File

@ -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, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. 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.

View File

@ -8,7 +8,7 @@ buildscript {
} }
dependencies { 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 compileSdkVersion 28
defaultConfig { defaultConfig {
minSdkVersion 16 minSdkVersion 21
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
} }
lintOptions { lintOptions {
disable 'InvalidPackage' disable 'InvalidPackage'
} }
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
} }

View File

@ -1,2 +1,4 @@
org.gradle.jvmargs=-Xmx1536M org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

View File

@ -1,26 +1,35 @@
package com.ryanheise.just_audio; 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.media.MediaTimestamp;
import android.os.Handler;
import io.flutter.plugin.common.EventChannel; import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.EventChannel.EventSink; import io.flutter.plugin.common.EventChannel.EventSink;
import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result; 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 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 Registrar registrar;
private final MethodChannel methodChannel; private final MethodChannel methodChannel;
private final EventChannel eventChannel; private final EventChannel eventChannel;
private EventSink eventSink; private EventSink eventSink;
private final Handler handler = new Handler(); private final Handler handler = new Handler();
private Runnable endDetector;
private final Runnable positionObserver = new Runnable() { private final Runnable positionObserver = new Runnable() {
@Override @Override
public void run() { public void run() {
@ -35,14 +44,31 @@ public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionL
}; };
private final String id; private final String id;
private final MediaPlayer player; private String url;
private PlaybackState state; private volatile PlaybackState state;
private PlaybackState stateBeforeSeek; private PlaybackState stateBeforeSeek;
private long updateTime; private long updateTime;
private int updatePosition; 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) { public AudioPlayer(final Registrar registrar, final String id) {
mainThread = Thread.currentThread();
this.registrar = registrar; this.registrar = registrar;
this.id = id; this.id = id;
methodChannel = new MethodChannel(registrar.messenger(), "com.ryanheise.just_audio.methods." + 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; state = PlaybackState.none;
player = new MediaPlayer();
player.setOnCompletionListener(this);
} }
private void checkForDiscontinuity() { private void checkForDiscontinuity() {
// TODO: Consider using player.setOnMediaTimeDiscontinuityListener()
// when available in SDK. (Added in API level 28)
final long now = System.currentTimeMillis(); final long now = System.currentTimeMillis();
final int position = getCurrentPosition(); final int position = getCurrentPosition();
final long timeSinceLastUpdate = now - updateTime; final long timeSinceLastUpdate = now - updateTime;
final long expectedPosition = updatePosition + timeSinceLastUpdate; final long expectedPosition = updatePosition + (long)(timeSinceLastUpdate * speed);
final long drift = position - expectedPosition; final long drift = position - expectedPosition;
// Update if we've drifted or just started observing // Update if we've drifted or just started observing
if (updateTime == 0L) { if (updateTime == 0L) {
broadcastPlayerState(); broadcastPlayerState();
} else if (drift < -100) { } else if (drift < -100) {
System.out.println("time discontinuity detected: " + drift); System.out.println("time discontinuity detected: " + drift);
setPlaybackState(PlaybackState.buffering); transition(PlaybackState.buffering);
} else if (state == PlaybackState.buffering) { } else if (state == PlaybackState.buffering) {
setPlaybackState(PlaybackState.playing); transition(PlaybackState.playing);
} }
} }
@Override
public void onCompletion(final MediaPlayer mp) {
setPlaybackState(PlaybackState.stopped);
}
@Override @Override
public void onMethodCall(final MethodCall call, final Result result) { public void onMethodCall(final MethodCall call, final Result result) {
final List<?> args = (List<?>)call.arguments; final List<?> args = (List<?>)call.arguments;
@ -105,11 +122,14 @@ public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionL
result.success(null); result.success(null);
break; break;
case "stop": case "stop":
stop(); stop(result);
result.success(null);
break; break;
case "setVolume": 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); result.success(null);
break; break;
case "seek": case "seek":
@ -125,20 +145,17 @@ public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionL
} }
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
e.printStackTrace(); e.printStackTrace();
result.error("Illegal state", null, null); result.error("Illegal state: " + e.getMessage(), null, null);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
result.error("Error", null, null); result.error("Error: " + e, null, null);
} }
} }
private void broadcastPlayerState() { private void broadcastPlayerState() {
final ArrayList<Object> event = new ArrayList<Object>(); final ArrayList<Object> event = new ArrayList<Object>();
// state
event.add(state.ordinal()); event.add(state.ordinal());
// updatePosition
event.add(updatePosition = getCurrentPosition()); event.add(updatePosition = getCurrentPosition());
// updateTime
event.add(updateTime = System.currentTimeMillis()); event.add(updateTime = System.currentTimeMillis());
eventSink.success(event); eventSink.success(event);
} }
@ -146,101 +163,243 @@ public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionL
private int getCurrentPosition() { private int getCurrentPosition() {
if (state == PlaybackState.none || state == PlaybackState.connecting) { if (state == PlaybackState.none || state == PlaybackState.connecting) {
return 0; return 0;
} else if (seekPos != null) { } else if (seekRequests.size() > 0) {
return seekPos; return seekRequests.peekFirst().pos;
} else { } else {
return player.getCurrentPosition(); return (int)(extractor.getSampleTime() / 1000);
} }
} }
private void setPlaybackState(final PlaybackState state) { private void transition(final PlaybackState newState) {
final PlaybackState oldState = this.state; transition(state, newState);
this.state = state; }
if (oldState != PlaybackState.playing && state == PlaybackState.playing) {
private void transition(final PlaybackState oldState, final PlaybackState newState) {
state = newState;
if (oldState != PlaybackState.playing && newState == PlaybackState.playing) {
startObservingPosition(); startObservingPosition();
} }
broadcastPlayerState(); broadcastPlayerState();
} }
public void setUrl(final String url, final Result result) throws IOException { private void bgTransition(final PlaybackState newState) {
setPlaybackState(PlaybackState.connecting); bgTransition(state, newState);
player.reset(); }
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
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 @Override
public void onPrepared(final MediaPlayer mp) { public void run() {
setPlaybackState(PlaybackState.stopped); transition(oldState, newState);
result.success(mp.getDuration());
} }
}); });
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) { public void play(final Integer untilPosition) {
// TODO: dynamically adjust the lag.
final int lag = 6;
final int start = getCurrentPosition();
if (untilPosition != null && untilPosition <= start) { if (untilPosition != null && untilPosition <= start) {
return; throw new IllegalArgumentException("untilPosition must be >= 0");
} }
player.start(); this.untilPosition = untilPosition;
setPlaybackState(PlaybackState.playing); switch (state) {
if (endDetector != null) { case stopped:
handler.removeCallbacks(endDetector); ensureStopped();
transition(PlaybackState.playing);
playThread = new PlayThread();
playThread.start();
break;
case paused:
synchronized (monitor) {
transition(PlaybackState.playing);
monitor.notifyAll();
} }
if (untilPosition != null) { break;
final int duration = Math.max(0, untilPosition - start - lag); default:
handler.postDelayed(new Runnable() { throw new IllegalStateException("Can call play only from stopped and paused states (" + state + ")");
@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);
} }
} }
}, duration);
private void ensureStopped() {
synchronized (monitor) {
try {
while (playThread != null) {
monitor.wait();
}
} catch (Exception e) {}
} }
} }
public void pause() { public void pause() {
player.pause(); switch (state) {
setPlaybackState(PlaybackState.paused); 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() { public void stop(final Result result) {
player.pause(); switch (state) {
player.seekTo(0); case stopped:
setPlaybackState(PlaybackState.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) { public void setVolume(final float volume) {
player.setVolume((float)volume, (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) { public void seek(final int position, final Result result) {
stateBeforeSeek = state; synchronized (monitor) {
seekPos = position; if (state == PlaybackState.none || state == PlaybackState.connecting) {
handler.removeCallbacks(positionObserver); throw new IllegalStateException("Cannot call seek in none or connecting states");
setPlaybackState(PlaybackState.buffering); }
player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() { if (state == PlaybackState.stopped) {
@Override ensureStopped();
public void onSeekComplete(final MediaPlayer mp) { }
seekPos = null; start = position;
setPlaybackState(stateBeforeSeek); if (seekRequests.size() == 0) {
stateBeforeSeek = null; stateBeforeSeek = state;
result.success(null); }
player.setOnSeekCompleteListener(null); 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() { public void dispose() {
player.release(); if (state != PlaybackState.stopped && state != PlaybackState.none) {
setPlaybackState(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() { private void startObservingPosition() {
@ -248,6 +407,217 @@ public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionL
handler.post(positionObserver); 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 { enum PlaybackState {
none, none,
stopped, stopped,
@ -256,4 +626,14 @@ public class AudioPlayer implements MethodCallHandler, MediaPlayer.OnCompletionL
buffering, buffering,
connecting connecting
} }
class SeekRequest {
public final int pos;
public final Result result;
public SeekRequest(int pos, Result result) {
this.pos = pos;
this.result = result;
}
}
} }

View File

@ -5,6 +5,7 @@ import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result; import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar; import io.flutter.plugin.common.PluginRegistry.Registrar;
import java.util.List;
/** JustAudioPlugin */ /** JustAudioPlugin */
public class JustAudioPlugin implements MethodCallHandler { public class JustAudioPlugin implements MethodCallHandler {
@ -24,7 +25,8 @@ public class JustAudioPlugin implements MethodCallHandler {
public void onMethodCall(MethodCall call, Result result) { public void onMethodCall(MethodCall call, Result result) {
switch (call.method) { switch (call.method) {
case "init": case "init":
String id = (String)call.arguments; final List<?> args = (List<?>)call.arguments;
String id = (String)args.get(0);
new AudioPlayer(registrar, id); new AudioPlayer(registrar, id);
result.success(null); result.success(null);
break; break;

File diff suppressed because it is too large Load Diff

1
example/.gitignore vendored
View File

@ -24,6 +24,7 @@
**/doc/api/ **/doc/api/
.dart_tool/ .dart_tool/
.flutter-plugins .flutter-plugins
.flutter-plugins-dependencies
.packages .packages
.pub-cache/ .pub-cache/
.pub/ .pub/

View File

@ -34,11 +34,11 @@ android {
defaultConfig { defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.ryanheise.just_audio_example" applicationId "com.ryanheise.just_audio_example"
minSdkVersion 16 minSdkVersion 21
targetSdkVersion 28 targetSdkVersion 28
versionCode flutterVersionCode.toInteger() versionCode flutterVersionCode.toInteger()
versionName flutterVersionName versionName flutterVersionName
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
} }
buildTypes { buildTypes {
@ -56,6 +56,6 @@ flutter {
dependencies { dependencies {
testImplementation 'junit:junit:4.12' testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
} }

View File

@ -5,7 +5,7 @@ buildscript {
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:3.2.1' classpath 'com.android.tools.build:gradle:3.5.0'
} }
} }

View File

@ -1,2 +1,4 @@
org.gradle.jvmargs=-Xmx1536M org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

View File

@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists 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

View File

@ -1,10 +1,7 @@
import 'dart:math';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:just_audio/just_audio.dart'; import 'package:just_audio/just_audio.dart';
import 'package:rxdart/rxdart.dart';
void main() => runApp(MyApp()); void main() => runApp(MyApp());
@ -14,11 +11,14 @@ class MyApp extends StatefulWidget {
} }
class _MyAppState extends State<MyApp> { class _MyAppState extends State<MyApp> {
final AudioPlayer _player = AudioPlayer(); final _volumeSubject = BehaviorSubject.seeded(1.0);
final _speedSubject = BehaviorSubject.seeded(1.0);
AudioPlayer _player;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_player = AudioPlayer();
_player.setUrl( _player.setUrl(
"https://s3.amazonaws.com/scifri-episodes/scifri20181123-episode.mp3"); "https://s3.amazonaws.com/scifri-episodes/scifri20181123-episode.mp3");
} }
@ -82,6 +82,7 @@ class _MyAppState extends State<MyApp> {
); );
}, },
), ),
Text("Track position"),
StreamBuilder<Duration>( StreamBuilder<Duration>(
stream: _player.durationStream, stream: _player.durationStream,
builder: (context, snapshot) { 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);
},
),
),
], ],
), ),
), ),

View File

@ -7,7 +7,7 @@ packages:
name: archive name: archive
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "2.0.10" version: "2.0.11"
args: args:
dependency: transitive dependency: transitive
description: description:
@ -21,7 +21,7 @@ packages:
name: async name: async
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "2.3.0" version: "2.4.0"
boolean_selector: boolean_selector:
dependency: transitive dependency: transitive
description: description:
@ -87,21 +87,21 @@ packages:
path: ".." path: ".."
relative: true relative: true
source: path source: path
version: "0.0.1" version: "0.0.2"
matcher: matcher:
dependency: transitive dependency: transitive
description: description:
name: matcher name: matcher
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "0.12.5" version: "0.12.6"
meta: meta:
dependency: transitive dependency: transitive
description: description:
name: meta name: meta
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "1.1.7" version: "1.1.8"
path: path:
dependency: transitive dependency: transitive
description: description:
@ -145,12 +145,12 @@ packages:
source: hosted source: hosted
version: "2.0.5" version: "2.0.5"
rxdart: rxdart:
dependency: transitive dependency: "direct main"
description: description:
name: rxdart name: rxdart
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "0.22.6" version: "0.23.1"
sky_engine: sky_engine:
dependency: transitive dependency: transitive
description: flutter description: flutter
@ -197,7 +197,7 @@ packages:
name: test_api name: test_api
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "0.2.5" version: "0.2.11"
typed_data: typed_data:
dependency: transitive dependency: transitive
description: description:
@ -220,5 +220,5 @@ packages:
source: hosted source: hosted
version: "3.5.0" version: "3.5.0"
sdks: sdks:
dart: ">=2.4.0 <3.0.0" dart: ">=2.6.0 <3.0.0"
flutter: ">=1.9.1+hotfix.5 <2.0.0" flutter: ">=1.9.1+hotfix.5 <2.0.0"

View File

@ -6,9 +6,8 @@ dependencies:
flutter: flutter:
sdk: 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 cupertino_icons: ^0.1.2
rxdart: ^0.23.1
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:

View File

@ -60,6 +60,9 @@
} else if ([@"setVolume" isEqualToString:call.method]) { } else if ([@"setVolume" isEqualToString:call.method]) {
[self setVolume:(float)[args[0] doubleValue]]; [self setVolume:(float)[args[0] doubleValue]];
result(nil); result(nil);
} else if ([@"setSpeed" isEqualToString:call.method]) {
[self setSpeed:(float)[args[0] doubleValue]];
result(nil);
} else if ([@"seek" isEqualToString:call.method]) { } else if ([@"seek" isEqualToString:call.method]) {
[self seek:[args[0] intValue] result:result]; [self seek:[args[0] intValue] result:result];
result(nil); result(nil);
@ -92,7 +95,7 @@
long long now = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0); long long now = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0);
int position = [self getCurrentPosition]; int position = [self getCurrentPosition];
long long timeSinceLastUpdate = now - _updateTime; long long timeSinceLastUpdate = now - _updateTime;
long long expectedPosition = _updatePosition + timeSinceLastUpdate; long long expectedPosition = _updatePosition + timeSinceLastUpdate; // TODO: * speed
long long drift = position - expectedPosition; long long drift = position - expectedPosition;
// Update if we've drifted or just started observing // Update if we've drifted or just started observing
if (_updateTime == 0L) { if (_updateTime == 0L) {
@ -257,6 +260,14 @@
[_player setVolume:volume]; [_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 { - (void)seek:(int)position result:(FlutterResult)result {
_stateBeforeSeek = _state; _stateBeforeSeek = _state;
_seekPos = position; _seekPos = position;

View File

@ -23,7 +23,8 @@
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
if ([@"init" isEqualToString:call.method]) { 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]; AudioPlayer* player = [[AudioPlayer alloc] initWithRegistrar:_registrar playerId:playerId];
result(nil); result(nil);
} else { } else {

View File

@ -46,8 +46,8 @@ import 'package:rxdart/rxdart.dart';
class AudioPlayer { class AudioPlayer {
static final _mainChannel = MethodChannel('com.ryanheise.just_audio.methods'); static final _mainChannel = MethodChannel('com.ryanheise.just_audio.methods');
static Future<MethodChannel> _createChannel(int id) async { static Future<MethodChannel> _init(int id) async {
await _mainChannel.invokeMethod('init', '$id'); await _mainChannel.invokeMethod('init', ['$id']);
return MethodChannel('com.ryanheise.just_audio.methods.$id'); return MethodChannel('com.ryanheise.just_audio.methods.$id');
} }
@ -69,22 +69,31 @@ class AudioPlayer {
final _playbackStateSubject = BehaviorSubject<AudioPlaybackState>(); final _playbackStateSubject = BehaviorSubject<AudioPlaybackState>();
double _volume = 1.0;
double _speed = 1.0;
/// Creates an [AudioPlayer]. /// Creates an [AudioPlayer].
factory AudioPlayer() => factory AudioPlayer() =>
AudioPlayer._internal(DateTime.now().microsecondsSinceEpoch); 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') _eventChannelStream = EventChannel('com.ryanheise.just_audio.events.$_id')
.receiveBroadcastStream() .receiveBroadcastStream()
.map((data) => _audioPlayerState = AudioPlayerState( .map((data) => _audioPlayerState = AudioPlayerState(
state: AudioPlaybackState.values[data[0]], state: AudioPlaybackState.values[data[0]],
updatePosition: Duration(milliseconds: data[1]), updatePosition: Duration(milliseconds: data[1]),
updateTime: Duration(milliseconds: data[2]), updateTime: Duration(milliseconds: data[2]),
speed: _speed,
)); ));
_eventChannelStreamSubscription = _eventChannelStreamSubscription =
_eventChannelStream.listen(_playerStateSubject.add); _eventChannelStream.listen(_playerStateSubject.add);
_playbackStateSubject _playbackStateSubject
.addStream(playerStateStream.map((state) => state.state).distinct()); .addStream(playerStateStream.map((state) => state.state).distinct());
playerStateStream.listen((state) {
print("state: $state");
});
} }
/// The duration of any media set via [setUrl], [setFilePath] or [setAsset], /// 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. /// A stream periodically tracking the current position of this player.
Stream<Duration> getPositionStream( Stream<Duration> getPositionStream(
[final Duration period = const Duration(milliseconds: 200)]) => [final Duration period = const Duration(milliseconds: 200)]) =>
Observable.combineLatest2<AudioPlayerState, void, Duration>( Rx.combineLatest2<AudioPlayerState, void, Duration>(
playerStateStream, playerStateStream,
Observable.periodic(period), // TODO: emit periodically only in playing state.
Stream.periodic(period),
(state, _) => state.position); (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. /// Loads audio media from a URL and returns the duration of that audio.
Future<Duration> setUrl(final String url) async { Future<Duration> setUrl(final String url) async {
_durationFuture = _durationFuture =
@ -170,10 +186,11 @@ class AudioPlayer {
} }
/// Stops the currently playing media such that the next [play] invocation /// 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 /// will start from position 0. It is legal to invoke this method only from
/// state except for: /// the following states:
/// ///
/// * [AudioPlaybackState.none] /// * [AudioPlaybackState.playing]
/// * [AudioPlaybackState.paused]
/// * [AudioPlaybackState.stopped] /// * [AudioPlaybackState.stopped]
Future<void> stop() async { Future<void> stop() async {
await _invokeMethod('stop'); await _invokeMethod('stop');
@ -181,9 +198,16 @@ class AudioPlayer {
/// Sets the volume of this player, where 1.0 is normal volume. /// Sets the volume of this player, where 1.0 is normal volume.
Future<void> setVolume(final double volume) async { Future<void> setVolume(final double volume) async {
_volume = volume;
await _invokeMethod('setVolume', [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 /// Seeks to a particular position. It is legal to invoke this method
/// from any state except for [AudioPlaybackState.none]. /// from any state except for [AudioPlaybackState.none].
Future<void> seek(final Duration position) async { Future<void> seek(final Duration position) async {
@ -218,18 +242,26 @@ class AudioPlayerState {
/// The position at [updateTime]. /// The position at [updateTime].
final Duration updatePosition; final Duration updatePosition;
/// The playback speed.
final double speed;
AudioPlayerState({ AudioPlayerState({
@required this.state, @required this.state,
@required this.updateTime, @required this.updateTime,
@required this.updatePosition, @required this.updatePosition,
@required this.speed,
}); });
/// The current position of the player. /// The current position of the player.
Duration get position => state == AudioPlaybackState.playing Duration get position => state == AudioPlaybackState.playing
? updatePosition + ? updatePosition +
(Duration(milliseconds: DateTime.now().millisecondsSinceEpoch) - (Duration(milliseconds: DateTime.now().millisecondsSinceEpoch) -
updateTime) updateTime) *
speed
: updatePosition; : updatePosition;
@override
String toString() => "{state=$state, updateTime=$updateTime, updatePosition=$updatePosition, speed=$speed}";
} }
/// Enumerates the different playback states of a player. /// Enumerates the different playback states of a player.

View File

@ -1,13 +1,27 @@
# Generated by pub # Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile # See https://dart.dev/tools/pub/glossary#lockfile
packages: 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: async:
dependency: transitive dependency: transitive
description: description:
name: async name: async
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "2.3.0" version: "2.4.0"
boolean_selector: boolean_selector:
dependency: transitive dependency: transitive
description: description:
@ -29,6 +43,20 @@ packages:
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "1.14.11" 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: flutter:
dependency: "direct main" dependency: "direct main"
description: flutter description: flutter
@ -39,20 +67,27 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" version: "0.0.0"
image:
dependency: transitive
description:
name: image
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.4"
matcher: matcher:
dependency: transitive dependency: transitive
description: description:
name: matcher name: matcher
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "0.12.5" version: "0.12.6"
meta: meta:
dependency: transitive dependency: transitive
description: description:
name: meta name: meta
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "1.1.7" version: "1.1.8"
path: path:
dependency: "direct main" dependency: "direct main"
description: description:
@ -74,6 +109,13 @@ packages:
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "1.8.0+1" version: "1.8.0+1"
petitparser:
dependency: transitive
description:
name: petitparser
url: "https://pub.dartlang.org"
source: hosted
version: "2.4.0"
platform: platform:
dependency: transitive dependency: transitive
description: description:
@ -94,7 +136,7 @@ packages:
name: rxdart name: rxdart
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "0.22.6" version: "0.23.1"
sky_engine: sky_engine:
dependency: transitive dependency: transitive
description: flutter description: flutter
@ -141,7 +183,7 @@ packages:
name: test_api name: test_api
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "0.2.5" version: "0.2.11"
typed_data: typed_data:
dependency: transitive dependency: transitive
description: description:
@ -156,6 +198,13 @@ packages:
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "2.0.8" version: "2.0.8"
xml:
dependency: transitive
description:
name: xml
url: "https://pub.dartlang.org"
source: hosted
version: "3.5.0"
sdks: sdks:
dart: ">=2.2.2 <3.0.0" dart: ">=2.6.0 <3.0.0"
flutter: ">=1.9.1+hotfix.5 <2.0.0" flutter: ">=1.9.1+hotfix.5 <2.0.0"

View File

@ -8,7 +8,7 @@ environment:
sdk: ">=2.1.0 <3.0.0" sdk: ">=2.1.0 <3.0.0"
dependencies: dependencies:
rxdart: ^0.22.6 rxdart: ^0.23.1
path: ^1.6.4 path: ^1.6.4
path_provider: ^1.4.5 path_provider: ^1.4.5
flutter: flutter: