IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Discussion :

action.MEDIA_BUTTON controle lecture


Sujet :

Android

  1. #1
    Membre éclairé
    Profil pro
    Inscrit en
    Novembre 2009
    Messages
    315
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Novembre 2009
    Messages : 315
    Par défaut action.MEDIA_BUTTON controle lecture
    Bonjour,

    Je teste actuellement la partie Media

    Voici un code qui teste la lecture d'un morceau de musique

    J'ai 4 buttons que j'ai ajouté au code et qui fonctionnent bien mais normalement je dois voir

    apparaitre aussi les boutons contrôle de lecture qui sont en rapport ave le receiver MediaControlReceiver définit ds le Manifest

    Seul le bouton de contrôle du volume est accessible .

    Si une idée est disponible , je suis preneur, Merci

    Voici le code AudioPlayerActivity.java et le Manifest

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    [
     package com.paad.mediaplayer;
    import java.io.IOException;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.app.PendingIntent;
    import android.content.BroadcastReceiver;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.graphics.Bitmap;
    import android.media.AudioManager;
    import android.media.AudioManager.OnAudioFocusChangeListener;
    import android.media.MediaMetadataRetriever;
    import android.media.MediaPlayer;
    import android.media.MediaPlayer.OnCompletionListener;
    import android.media.RemoteControlClient;
    import android.media.RemoteControlClient.MetadataEditor;
    import android.media.audiofx.BassBoost;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    @SuppressLint("NewApi")
    public class AudioPlayerActivity extends Activity {
      static final String TAG = "PlayerActivity";
      //Bitmap pochette = audio.png;
      Bitmap pochette = null;
      
      private ActivityMediaControlReceiver activityMediaControlReceiver;
      private MediaPlayer mediaPlayer;
      private RemoteControlClient myRemoteControlClient;
      
      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.audioplayer);
        /**
         * Listing 15-6: Setting the volume control stream for an Activity
         */
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        registerRemoteControlClient();
        configureAudio();
        
        Button buttonPlay = (Button)findViewById(R.id.buttonPlay);
        buttonPlay.setOnClickListener(new OnClickListener() {
          public void onClick(View v) {
            play();
          }
        });
        
        Button buttonBass = (Button)findViewById(R.id.buttonBassBoost);
        buttonBass.setOnClickListener(new OnClickListener() {
          public void onClick(View v) {
            bassBoost();
          }
        });
        
        Button buttonPause = (Button)findViewById(R.id.buttonPause);
        buttonPause.setOnClickListener(new OnClickListener() {
          public void onClick(View v) {
           pause();
          }
        });
        
        Button buttonStop = (Button)findViewById(R.id.buttonStop);
        buttonStop.setOnClickListener(new OnClickListener() {
          public void onClick(View v) {
            stop();
          }
        });
      }
      
      /**
       * Listing 15-9: Media button press Broadcast Receiver implementation
       */
      public class ActivityMediaControlReceiver extends BroadcastReceiver {
       public ActivityMediaControlReceiver() {
      // TODO Auto-generated constructor stub
            super ();
            Log.d("BROADReceiver","broad");
     }
         
        @Override
        public void onReceive(Context context, Intent intent) {
          Log.d("ONReceiver", intent.toString()); 
          if (MediaControlReceiver.ACTION_MEDIA_BUTTON.equals(
              intent.getAction())) {
            KeyEvent event =
              (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
            
             Log.d("Receiver", event.toString());
          
            switch (event.getKeyCode()) {
              case (KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) : 
                if (mediaPlayer.isPlaying())
                  pause();
                else
                  play();
                break;
              case (KeyEvent.KEYCODE_MEDIA_PLAY) : 
                play(); break;
              case (KeyEvent.KEYCODE_MEDIA_PAUSE) : 
                pause(); break;
              case (KeyEvent.KEYCODE_MEDIA_NEXT) : 
                skip(); break;
              case (KeyEvent.KEYCODE_MEDIA_PREVIOUS) : 
                previous(); break;
              case (KeyEvent.KEYCODE_MEDIA_STOP) : 
                stop(); break;
              default: break;
            }
          }
        }
      }
      
      @Override
      protected void onResume() {
        super.onResume();
        /**
         * Listing 15-10: Media button press Receiver manifest declaration
         */
        Log.d("RESUME", "resume");
        // Register the Media Button Event Receiver to 
        // listen for media button presses.
        AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        
        ComponentName component = new ComponentName(this, MediaControlReceiver.class);
        am.registerMediaButtonEventReceiver(component);
        // Register a local Intent Receiver that receives media button
        // presses from the Receiver registered in the manifest.
        activityMediaControlReceiver = new ActivityMediaControlReceiver();
        IntentFilter filter = 
          new IntentFilter(MediaControlReceiver.ACTION_MEDIA_BUTTON);
        registerReceiver(activityMediaControlReceiver, filter);
        //
        
        IntentFilter noiseFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
        registerReceiver(new NoisyAudioStreamReceiver(), noiseFilter);
      }
      
      public void play() {    
        /**
         * Listing 15-11: Requesting the audio focus
         */
     Log.d("PLAY", "play");
        AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        // Request audio focus for playback
        int result = am.requestAudioFocus(focusChangeListener,
                       // Use the music stream.
                       AudioManager.STREAM_MUSIC,
                       // Request permanent focus.
                       AudioManager.AUDIOFOCUS_GAIN);
           
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
          mediaPlayer.start();
        }
        
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) myRemoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
        //if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) myRemoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_BUFFERING);
      }
      
      /**
       * Listing 15-12: Responding to the loss of audio focus
       */
      private OnAudioFocusChangeListener focusChangeListener = 
        new OnAudioFocusChangeListener() {
        
        public void onAudioFocusChange(int focusChange) {
          AudioManager am = 
            (AudioManager)getSystemService(Context.AUDIO_SERVICE);
          
          switch (focusChange) {
            case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
              // Lower the volume while ducking.
              mediaPlayer.setVolume(0.2f, 0.2f);
              break;
            case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) : 
              pause();
              break;
            case (AudioManager.AUDIOFOCUS_LOSS) :
              stop();
              ComponentName component = 
                new ComponentName(AudioPlayerActivity.this,
                  MediaControlReceiver.class);
              am.unregisterMediaButtonEventReceiver(component);
              break;
            case (AudioManager.AUDIOFOCUS_GAIN) : 
              // Return the volume to normal and resume if paused.
              mediaPlayer.setVolume(1f, 1f);
              mediaPlayer.start();
              break;
            default: break;
          }
        }
      };
      
      public void stop() {
        mediaPlayer.stop();
        myRemoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
        
        /**
         * Listing 15-13: Abandoning audio focus
         */
        Log.d("STOP", "stop");
        AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        am.abandonAudioFocus(focusChangeListener);
      }
      
      /**
       * Listing 15-14: Pausing output when the headset is disconnected
       */
      private class NoisyAudioStreamReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
          if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals
            (intent.getAction())) {
            pause();
          }
        }
      }
      
      private void registerRemoteControlClient() {
        /**
         * Listing 15-15: Registering a Remote Control Client
         */
        AudioManager am = 
          (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        // Create a Pending Intent that will broadcast the 
        // media button press action. Set the target component 
        // to your Broadcast Receiver. 
        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        ComponentName component = 
          new ComponentName(this, MediaControlReceiver.class);
        mediaButtonIntent.setComponent(component);
        PendingIntent mediaPendingIntent =
           PendingIntent.getBroadcast(getApplicationContext(), 0,    
                                      mediaButtonIntent, 0);
        // Create a new Remote Control Client using the
        // Pending Intent and register it with the
        // Audio Manager
        myRemoteControlClient = 
          new RemoteControlClient(mediaPendingIntent);
        am.registerRemoteControlClient(myRemoteControlClient);
        
        /**
         * Listing 15-16: Configuring the Remote Control Client playback controls
         */
        myRemoteControlClient.setTransportControlFlags(
          RemoteControlClient.FLAG_KEY_MEDIA_PLAY|
          RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE|
          RemoteControlClient.FLAG_KEY_MEDIA_REWIND|
          RemoteControlClient.FLAG_KEY_MEDIA_FAST_FORWARD |
          RemoteControlClient.FLAG_KEY_MEDIA_STOP);
      }
      private void setRemoteControlMetadata(Bitmap artwork, 
          String album, String artist, long trackNumber) {
        /**
         * Listing 15-17: Applying changes to the Remote Control Client metadata
         */
        MetadataEditor editor = myRemoteControlClient.editMetadata(false);
        editor.putBitmap(MetadataEditor.BITMAP_KEY_ARTWORK, artwork);
        editor.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, album);
        editor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, artist);
        editor.putLong(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER, 
                       trackNumber);
        editor.apply();
      }
      
      private void bassBoost() {
        /**
         * Listing 15-22: Applying audio effects
         */
        int sessionId = mediaPlayer.getAudioSessionId();
        short boostStrength = 500;
        int priority = 0;
        BassBoost bassBoost = new BassBoost (priority, sessionId);
        bassBoost.setStrength(boostStrength);
        bassBoost.setEnabled(true);
      }
      
      private void configureAudio() {
        try {      
          mediaPlayer = new MediaPlayer();
          mediaPlayer.setDataSource("/sdcard/test.mp3");
          mediaPlayer.prepare();
          
          // TODO setRemoteControlMetadata();
          setRemoteControlMetadata(pochette,"Sleep Away","Bobo Acri", 320);
          
          mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
              AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
              am.abandonAudioFocus(focusChangeListener);
            }
          });
        } catch (IllegalArgumentException e) {
          Log.d(TAG, "Illegal Argument Exception: " + e.getMessage());
        } catch (SecurityException e) {
          Log.d(TAG, "Security Exception: " + e.getMessage());
        } catch (IllegalStateException e) {
          Log.d(TAG, "Illegal State Exception: " + e.getMessage());
        } catch (IOException e) {
          Log.d(TAG, "IO Exception: " + e.getMessage());
        }
      }
      
      public void pause() {
        mediaPlayer.pause();
        myRemoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED);
        Log.d("PAUSE", "pause");
      }
      
      public void skip() {
        // TODO Move to the next audio file.
        // TODO Use setRemoteControlMetadata to update the remote control metadata.
      }
      
      public void previous() {
        // TODO Move to the previous audio file.
        // TODO Use setRemoteControlMetadata to update the remote control metadata.
      }
    }
      
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
     
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="<a href="http://schemas.android.com/apk/res/android" target="_blank">http://schemas.android.com/apk/res/android</a>"
      package="com.paad.mediaplayer"
      android:versionCode="1"
      android:versionName="1.0" >
      <uses-sdk android:targetSdkVersion="17" />
     
      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
      <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" android:debuggable="true">
     <receiver android:name=".MediaControlReceiver">
       <intent-filter android:priority="1000000000000000">
         <action android:name="android.intent.action.MEDIA_BUTTON"/>
       </intent-filter>
     </receiver>
        <activity
          android:label="AudioPlayer"
          android:name=".AudioPlayerActivity" >
          <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
        </activity>
     
     
      </application>
    </manifest>

  2. #2
    Membre éclairé
    Profil pro
    Inscrit en
    Novembre 2009
    Messages
    315
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Novembre 2009
    Messages : 315
    Par défaut
    Pas de musicien à bord ??

Discussions similaires

  1. Appeler une action via controller::action() ?
    Par Khleo dans le forum MVC
    Réponses: 2
    Dernier message: 20/02/2013, 17h38
  2. Réponses: 1
    Dernier message: 29/11/2010, 09h21
  3. action updown control
    Par Invité dans le forum Windows
    Réponses: 41
    Dernier message: 12/11/2009, 23h39
  4. Variables communes aux actions du controller
    Par Louis-Guillaume Morand dans le forum Zend Framework
    Réponses: 2
    Dernier message: 25/09/2007, 23h34
  5. Faire une action sur Control + C
    Par bluecurve dans le forum Langage
    Réponses: 1
    Dernier message: 20/07/2006, 00h19

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo