Skip to content

Instantly share code, notes, and snippets.

@shekaroppo
Created July 29, 2016 13:00
Show Gist options
  • Select an option

  • Save shekaroppo/f8d057bb4fd6fd56c6f0e0b90800dde6 to your computer and use it in GitHub Desktop.

Select an option

Save shekaroppo/f8d057bb4fd6fd56c6f0e0b90800dde6 to your computer and use it in GitHub Desktop.

Media Playback

  • The Basics

    • MediaPlayer: This class is the primary API for playing sound and video.
    • AudioManager:This class manages audio sources and audio output on a device.
  • Manifest Declarations

    • Internet Permission

      <uses-permission android:name="android.permission.INTERNET" />
      
    • Wake Lock Permission - If your player application needs to keep the screen from dimming or the processor from sleeping, or uses the MediaPlayer.setScreenOnWhilePlaying() or MediaPlayer.setWakeMode()methods, you must request this permission.

      <uses-permission android:name="android.permission.WAKE_LOCK" />
      
  • Using MediaPlayer

    • An object of this class can fetch, decode, and play both audio and video with minimal setup.

    • It supports several different media sources such as:

      • Local resources
      • Internal URIs, such as one you might obtain from a Content Resolver
      • External URLs (streaming)
    • Play audio that's available as a local raw resource saved in res/raw/

      MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
      mediaPlayer.start(); // no need to call prepare(); create() does that for you
      
    • Play from a URI available locally in the system obtained through a Content Resolver

      Uri myUri = ....; // initialize Uri here
      MediaPlayer mediaPlayer = new MediaPlayer();
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mediaPlayer.setDataSource(getApplicationContext(), myUri);
      mediaPlayer.prepare();
      mediaPlayer.start();
      
    • Playing from a remote URL via HTTP streaming

      String url = "http://........"; // your URL here
      MediaPlayer mediaPlayer = new MediaPlayer();
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mediaPlayer.setDataSource(url);
      mediaPlayer.prepare(); // might take long! (for buffering, etc)
      mediaPlayer.start();
      

      Note: If you're passing a URL to stream an online media file, the file must be capable of progressive download.

      Caution: You must either catch or pass IllegalArgumentException and IOException when usingsetDataSource(), because the file you are referencing might not exist.

    • Asynchronous Preparation

      • prepare() non async
      • onPrepared() async
    • Managing State

      • create a new MediaPlayer :idle state.
      • setDataSource(), bringing it to the Initialized state
      • When prepare() or prepareAsync() is done preparing, it will then enter the Prepared state,
      • start() to make it play the media.
      • When you call stop(), you cannot call start() again until you prepare theMediaPlayer again.
    • Releasing the MediaPlayer

      mediaPlayer.release();
      mediaPlayer = null;
      
    • Using a Service with MediaPlayer

      • If you want your media to play in the background even when your application is not onscreen you must start a Service.
      • Running asynchronously
        • All work in a Service is done in a single thread
        • if you're running an activity and a service from the same application, they use the same thread (the "main thread") by default
      • Using wake locks
        • If your service is playing or streaming music, you want to prevent the system from shut off any of the phone's features that are necessary, like the CPU and the WiFi hardware.
        • A wake lock is a way to signal to the system that your application is using some feature that should stay available even if the phone is idle.
        mMediaPlayer = new MediaPlayer();
        // ... other initialization here ...
        mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
         .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
        wifiLock.acquire();
        
        • When no longer need it call
        wifiLock.release();
        
      • Running as a foreground service
        • A foreground service holds a higher level of importance within the system—the system will almost never kill the service, because it is of immediate importance to the user.
        • When running in the foreground, the service also must provide a status bar notification to ensure that users are aware of the running service and allow them to open an activity that can interact with the service.
        • In order to turn your service into a foreground service, you must create a Notification for the status bar and call startForeground() from the Service.
        • Release it by calling
        stopForeground(true);
        
      • Handling audio focus
        • Starting with Android 2.2, the platform offers a way for applications to negotiate their use of the device's audio output. This mechanism is called Audio Focus.
        • When your application needs to output audio such as music or a notification, you should always request audio focus. Once it has focus, it can use the sound output freely, but it should always listen for focus changes. If it is notified that it has lost the audio focus, it should immediately either kill the audio or lower it to a quiet level (known as "ducking"—there is a flag that indicates which one is appropriate) and only resume loud playback after it receives focus again.
      • Performing cleanup
        • public class MyService extends Service {
        MediaPlayer mMediaPlayer;
        // ...
        @Override
        public void onDestroy() {
            if (mMediaPlayer != null) mMediaPlayer.release();
           }
        }
        
      • Handling the AUDIO_BECOMING_NOISY Intent Screenshot Screenshot
    • Controls Everywhere

      • Headphone and bluetooth controls(Media buttons)
        • android.intent.action.MEDIA_BUTTON broadcast sent by system
        • MediaButtonReciever
  • Background playback

    • Services
      • Create (One time)
      • Play(When user hit play button)
      • Pause
      • Stop(Remove, clean up)
        • Swiping away notification
        • closing app
    • Features
      • Audio focus
      • Noisy broadcast
      • Media ButtonsRECIVER(MEDIABUTTONBROADCAST)
  • Component

    • MediaPlayer
    • MediaBrowser

Ref

https://plus.google.com/+IanLake/posts/4xMwLvHzj7P http://developer.android.com/intl/es/reference/android/media/MediaPlayer.html http://developer.android.com/intl/es/guide/topics/media/mediaplayer.html https://www.youtube.com/watch?v=FBC1FgWe5X4 https://plus.google.com/+IanLake/posts/Y2k4gttBg79 https://www.youtube.com/watch?v=G6pFai3ll9E&index=15&list=PLWz5rJ2EKKc_Tt7q77qwyKRgytF1RzRx8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment