You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Android:Google Play Music搜索播放单曲(非电台)技术问题咨询

解决Google Play Music通过Intent直接播放单曲的问题

嘿,我来帮你搞定这个困扰!你现在遇到的问题是因为MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH这个Intent Action在Google Play Music里的默认行为就是启动电台——哪怕你指定了媒体焦点为音频项,应用还是会优先触发电台模式,而不是直接播放你搜索的单曲。

解决方案:通过媒体库查询歌曲URI,直接启动播放

要实现仅播放指定单曲,我们可以先通过系统媒体库查询到目标歌曲的Content URI,再用ACTION_VIEW Intent调用Google Play Music直接播放这首歌。具体步骤和代码如下:

  1. 查询匹配的歌曲:使用ContentResolver搜索系统媒体库中符合你查询条件的歌曲,获取它的唯一URI。
  2. 启动播放Intent:用获取到的URI创建ACTION_VIEW Intent,指定Google Play Music作为目标应用,这样就能直接播放单曲了。

示例代码:

// 你的歌曲查询关键词
String songQuery = "你要播放的歌曲名";

// 查询系统媒体库,获取匹配歌曲的URI
Uri mediaUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = {
    MediaStore.Audio.Media._ID,
    MediaStore.Audio.Media.TITLE,
    MediaStore.Audio.Media.ARTIST // 可选,用来更精确匹配
};
// 这里可以根据需要调整查询条件,比如同时匹配歌曲名和艺术家
String selection = MediaStore.Audio.Media.TITLE + " LIKE ?";
String[] selectionArgs = {"%" + songQuery + "%"};

Cursor songCursor = getContentResolver().query(
    mediaUri,
    projection,
    selection,
    selectionArgs,
    null
);

if (songCursor != null && songCursor.moveToFirst()) {
    // 获取歌曲ID并构建Content URI
    long songId = songCursor.getLong(songCursor.getColumnIndex(MediaStore.Audio.Media._ID));
    Uri targetSongUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, songId);
    
    // 创建播放Intent,指定Google Play Music应用
    Intent playSingleSongIntent = new Intent(Intent.ACTION_VIEW);
    playSingleSongIntent.setDataAndType(targetSongUri, "audio/*");
    playSingleSongIntent.setPackage("com.google.android.music"); // 确保只调用Google Play Music
    
    // 启动Intent
    startActivity(playSingleSongIntent);
    
    songCursor.close();
} else {
    // 处理未找到匹配歌曲的情况,比如提示用户
    Toast.makeText(this, "未找到匹配的歌曲", Toast.LENGTH_SHORT).show();
}

注意事项

  • 权限问题:如果你的应用运行在Android 10(API 29)及以上版本,需要申请READ_EXTERNAL_STORAGE权限来访问系统媒体库;Android 13及以上可以申请更细化的READ_MEDIA_AUDIO权限。
  • 精确匹配:如果查询的歌曲名有重名,建议在查询条件中加入艺术家名称(MediaStore.Audio.Media.ARTIST),避免播放错误的歌曲。

内容的提问来源于stack exchange,提问作者Ivan Mihov

火山引擎 最新活动