GithubHelp home page GithubHelp logo

audioview's Introduction

Download

AudioView

Simple Android audio view with a few controls. Basically it's a MediaPlayer wrapper. You can choose AudioView2 and start a AudioService to start MediaPlayer in service. See below for more info (and demo app).

See picture

See demo app

Usage with Gradle

  1. Add dependency
dependencies {
    implementation 'com.4ert:audioview:{latest-version}'
}
  1. Add layout
<com.keenfin.audioview.AudioView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
  1. Set file data source
audioView.setDataSource("/path/to/file");
audioView.setDataSource(Uri);
audioView.setDataSource(FileDescriptor);
audioView.setDataSource(List<String/Uri/FileDescriptor>);
  1. Control playback if needed
audioView.start();
audioView.pause();
audioView.stop();
audioView.previousTrack();
audioView.nextTrack();

Usage AudioView2 in AudioService

Multiple AudioView2 with different tags can attach to service and play through it, but only one at a time. It's useful while placing AudioView2 in list or recycler view.

  1. Create AudioView2 in xml or by code
<com.keenfin.audioview.AudioView2
    android:id="@+id/audioview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

2. **Start AudioService to handle playback (optional)**

``` java
Intent audioService = new Intent(this, AudioService.class);
audioService.setAction(AudioService.ACTION_START_AUDIO);
startService(audioService);
  1. Assign tag for view and attach to service
AudioView2 audio = itemView.findViewById(R.id.audioview);
audio.setTag(position);
if (!audio.attached())
    audio.setUpControls();
try {
    audio.setDataSource(object.getPath());
} catch (IOException ignored) {
}
  1. Stop service when you do not need it anymore (optional)
Intent audioService = new Intent(this, AudioService.class);
stopService(audioService);

There is a default behaviour for AudioView2 to start service automatically if it is not running yet. You can disable this by setting AudioView2.setAutoStartServie(false), but you can not omit 2 and 5 steps in this case.

Attach to service to implement your own behaviour

You can attach to AudioService to implement your own view or other behaviour.

  1. Add service connection
private ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        mService = ((AudioService.AudioServiceBinder) iBinder).getService();
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        mService = null;
    }
};
  1. Bind/unbind to service
private void bindAudioService() {
    Intent intent = new Intent(getContext(), AudioService.class);
    getApplicationContext().bindService(intent, mServiceConnection, 0);
}

private void unbindAudioService() {
    try {
        getApplicationContext().unbindService(mServiceConnection);
    } catch (Exception ignored) {
    }
}
  1. Add broadcast receiver to handle events
private BroadcastReceiver mAudioReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int status = intent.getIntExtra("status", -1);
        int status = intent.getIntExtra("tag", -1);
        switch (status) {
            case AUDIO_PREPARED:
            case AUDIO_STARTED:
            case AUDIO_PAUSED:
            case AUDIO_STOPPED:
            case AUDIO_PROGRESS_UPDATED:
            case AUDIO_COMPLETED:
            case AUDIO_TRACK_CHANGED:
                break;
        }
    }
};
  1. Register/unregister receiver
private void registerAudioReceiver() {
    getContext().registerReceiver(mAudioReceiver, filter);
}

private void unregisterAudioReceiver() {
    try {
        getContext().unregisterReceiver(mAudioReceiver);
    } catch (Exception ignored) {
    }
}

Or send command to service to control playback

  • ACTION_START_AUDIO
  • ACTION_PAUSE_AUDIO
  • ACTION_STOP_AUDIO
  • ACTION_PREVIOUS_AUDIO
  • ACTION_NEXT_AUDIO
  • ACTION_CONTROL_AUDIO (to start/pause depending on current state)
  • ACTION_DESTROY_SERVICE (to immediately destroy)

Audio notification for service

For AudioView2 and associated service foreground notification is applied. There are default playback controls plus close icon to stop and destroy service. You can setup following parameters through service intent or by proxying them over AudioView2:

AUDIO_NOTIFICATION_CHANNEL_ID

AudioView2.setServiceNotificationId(int id)

Integer to append to default string channel id for Android 8+

AUDIO_NOTIFICATION_ICON_RES

AudioView2.setServiceNotificationIcon(int icon)

Drawable integer resource to show in status bar for notification

AUDIO_NOTIFICATION_SHOW_CLOSE

AudioView2.setServiceNotificationShowClose(boolean showClose)

Boolean to show close service button or not

AUDIO_NOTIFICATION_MINIFIED

AudioView2.setServiceNotificationMinified(boolean minified)

Boolean to hide previous/next and title views

Styles & options

primaryColor

Set default color for FAB, SeekBar and ProgressBar. By default it uses colorAccent from AppTheme.

minified

Use alternative version of layout if true.

customLayout

Specify custom player layout reference. Must contain:

  • ImageButton R.id.play;
  • SeekBar R.id.progress;
  • ProgressBar R.id.indeterminate.

Optionally:

  • TextViews R.id.title, R.id.time, R.id.total_time;
  • View R.id.rewind, R.id.forward

If R.id.time defined, then it shows "time/total time" like "00:01/03:55".

If R.id.total_time defined also, then R.id.time shows time like "00:01" and total time shows total like "03:55"

Mutually exclusive with minified. If you want tint your own colors, just omit primaryColor.

...
app:customLayout="@layout/my_custom_layout"
...

customPlayIcon

Set resource of play icon.

customPauseIcon

Set resource of pause icon.

selectControls

Show (true by default) or hide rewind/forward buttons. Not available if minified.

showTitle

Show song's title if there is one. Default is true.

<com.keenfin.audioview.AudioView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:minified="true"
    app:primaryColor="@android:color/holo_blue_ligh"
    app:selectControls="false"
    app:showTitle="false"
    app:customPlayIcon="@drawable/my_play_icon"
    app:customPauseIcon="@drawable/my_pause_icon"/>

setLoop(boolean)

Loop playlist (or single file).

audioview's People

Contributors

4ertuk avatar adinar avatar jeuler avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

audioview's Issues

render issue for layout in my androix

java.lang.NoClassDefFoundError: Could not initialize class android.media.MediaPlayer
at com.keenfin.audioview.AudioView.initMediaPlayer(AudioView.java:141)
at com.keenfin.audioview.AudioView.onAttachedToWindow(AudioView.java:221)
at android.view.View.dispatchAttachedToWindow(View.java:19575)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3430)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.AttachInfo_Accessor.setAttachInfo(AttachInfo_Accessor.java:42)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:335)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:396)
at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:209)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:608)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$6(RenderTask.java:734)
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

Issue in UI on playing audio from url

When I set data source as url in using Uri.parse(url) AudioView progress bar keeps loading & shows infinity symbol but when play button is clicked, audioview plays audio & infinity symbol changes to elapsed/total but seekbar keeps loading & unable to seek.

Crash in ViewPager

How I can setup AudioView in ViewPager? Should I use AudioView2? Or can go with AudioView?
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. I am receiving this when I am trying to go with AudioView inside FragmentStatePagerAdapter.

java.lang.IllegalThreadStateException

I used AudioView2, when start、pause and then start again crashed
Log :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: biz.seeyou, PID: 2982
java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:744)
at com.keenfin.audioview.AudioService.startUpdateThread(AudioService.java:175)
at com.keenfin.audioview.AudioService.start(AudioService.java:344)
at com.keenfin.audioview.AudioService.controlAudio(AudioService.java:216)
at com.keenfin.audioview.AudioView2.onClick(AudioView2.java:209)
at android.view.View.performClick(View.java:6291)
at android.view.View$PerformClick.run(View.java:24931)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)

setDataSource(List<Uri>) kotlin not working

I`am trying to implement bulk adding Uris using this code
val list : MutableList = ArrayList()
list.add(Uri.parse("file:///data/user/0/com.example/cache/audio2878360197049414151.tmp"))

binding.audioView.setDataSource(list)

But it returns this error
AudioView supports only String, Uri, FileDescriptor data sources now.

Playing next / previous track

Is there any built in function that plays next / previous track programmatically in AudioView if a list of audios was provided ?

Music stops on sreen rotation.

Subj.

P.S.:

  1. Раздел "From network uri" - линейный прогресс не останавливается. Пауза не нажимается. Время 89:48:04 всегда.
  2. Раздел "With custom layout" - круговой прогресс никогда не исчезает

AudioPreparedListener

I #2 I've added the listener for the AudioPrepared event. I think it is useful. But don't see it in 0.4 release. That is okay? :)

java.lang.NoClassDefFoundError: Could not initialize class android.media.MediaPlayer

At layout editor mode , i`am facing this issue when layout is rendering
java.lang.NoClassDefFoundError: Could not initialize class android.media.MediaPlayer
 at com.keenfin.audioview.AudioView.initMediaPlayer(AudioView.java:141)   at com.keenfin.audioview.AudioView.onAttachedToWindow(AudioView.java:221)

Xml code :
<com.keenfin.audioview.AudioView
android:id="@+id/audioView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="@drawable/audio_view_bg"
app:customLayout="@layout/audio_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/constraintLayout"/>

I think isInEditMode() functions is not working properly ins this case

Android 12 pending intent issue

Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.

Time is not showing

Hi! It's me again! I've tested your fix for #8 and it is working. But now I don't have time for track. :(
2019-04-19_15-24-19

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.