【问题标题】:Launching Media Player using Intent使用 Intent 启动媒体播放器
【发布时间】:2013-06-12 13:12:47
【问题描述】:

我正在开发我的第一个 Android 应用。它是录音应用程序。我正在像这样使用 MediaRecord 录制声音:

mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }

        mRecorder.start();

我还有另一个活动可以播放这些录制的声音(.3gpp 文件)。在这个活动中,有一个包含我录制的声音的 ListView。我想用手机上安装的任何音乐播放器播放声音。这是我的代码: (此代码来源:https://stackoverflow.com/a/3367231/556169

Intent intent = new Intent();  
intent.setAction(android.content.Intent.ACTION_VIEW);  
File file = new File((String) ((TextView) item).getText());  
intent.setDataAndType(Uri.fromFile(file), "audio/*");  
startActivity(intent);

但我收到“音乐播放器无法播放此媒体类型”错误。

当我浏览这些音频文件并通过我的文件资源管理器播放它们时,它运行良好(意思是,我正在成功录制声音)。但是当我在我的应用程序中使用 Intent 时,我得到了错误。

附加 我不能使用MediaStore.INTENT_ACTION_MUSIC_PLAYER,因为它已被弃用。 我不能使用 Intent.CATEGORY_APP_MUSIC因为它需要 min API lvl 15 。我的项目的最低 API 级别应该是 8。

【问题讨论】:

    标签: android android-intent audio-player android-music-player


    【解决方案1】:

    我认为最好的选择是使用选择器活动,用户可以在其中选择他最喜欢的媒体播放器。

    Intent viewIntent = new Intent(Intent.ACTION_VIEW);
    File file = new File((String) ((TextView) item).getText());
    viewIntent.setDataAndType(Uri.fromFile(file), "audio/*");
    startActivity(Intent.createChooser(viewIntent, null));
    

    顺便说一句,这种传递文件名的方式对我来说似乎有点奇怪。我会考虑改变它。

    我不确定,但如果你声明了相应的意图过滤器,你应该能够在选择器中看到你自己的播放器。

    【讨论】:

      【解决方案2】:

      您仍然可以使用已弃用的 Intent 来定位低于 15 的 API 级别,然后使用新的 Intent 来定位更新的 API 级别。为此,只需在您的代码中使用如下检查:

      if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 )  {
         // use the [MediaStore.INTENT_ACTION_MUSIC_PLAYER] intent
      }
      else  {
         // use the [Intent.CATEGORY_APP_MUSIC] intent
      }
      

      只需确保您的 TargetAPI 为 15 或更高;你的 MinAPI 可以是 8。

      【讨论】:

      • 我昨天试过了,有问题。在 Galaxy Note 2 (Android 4.1.2) 上,我收到 No Activity found to handle Intent { act=android.intent.category.APP_MUSIC dat=file:///audiorecordtest20130612145343.3gp typ=audio/* } 。在 Galaxy S2 (Android 4.1.2) 上,我的音乐播放器启动然后突然关闭。
      • ` `
      • 这似乎是一些三星设备未正确注册其音乐播放器的问题。请参阅here 了解更多信息。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多