Android媒体播放---Media playback(五)

处理AUDIO_BECOMING_NOISY意图

一些精心编写的应用程序在发生音频吵杂的事件(通过外部扬声器输出)时,能够自动的终止播放。例如,在用户正在使用耳麦听音乐时,而耳麦偶然与设备的连接断开,就可能发生这种情况。但是这种行为不会自动发生。如果你没有实现这个功能,音频就可能通过外部扬声器来输出,这可能是用户不想要的。

通过处理ACTION_AUDIO_BECOMING_NOISY意图,你能够确保在发生这种情况时,终止音乐的播放。通过把下列内容添加到你应用清单中,就能够注册一个接受器:

<receiver android:name=".MusicIntentReceiver">

   <intent-filter>

      <action android:name="android.media.AUDIO_BECOMING_NOISY" />

   </intent-filter>

</receiver>

这个注册的MusicIntenReceiver类做为该Intent的广播接收器。然后应该实现这个类:

public class MusicIntentReceiver implements android.content.BroadcastReceiver {

   @Override

   public void onReceive(Context ctx, Intent intent) {

      if (intent.getAction().equals(

                    android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {

          // signal your service to stop playback

          // (via an Intent, for instance)

      }

   }

}

 

从内容解析器(Content Resolver)中接收媒体数据

在媒体播放应用程序中,可以使用另外一种有用的功能来获取用户设备上的音乐。通过查询ContentResolver来获取外部媒体:

ContentResolver contentResolver = getContentResolver();

Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

Cursor cursor = contentResolver.query(uri, null, null, null, null);

if (cursor == null) {

    // query failed, handle error.

} else if (!cursor.moveToFirst()) {

    // no media on the device

} else {

    int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);

    int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);

    do {

       long thisId = cursor.getLong(idColumn);

       String thisTitle = cursor.getString(titleColumn);

       // ...process entry...

    } while (cursor.moveToNext());

}

通过以下方式来使用这个MediaPlayer对象:

long id =/* retrieve it from somewhere */;
Uri contentUri =ContentUris.withAppendedId(
        android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
 
mMediaPlayer =newMediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setDataSource(getApplicationContext(), contentUri);
 
// ...prepare and start...

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值