【问题标题】:How to play Audio file from resource directory in android如何从android中的资源目录播放音频文件
【发布时间】:2017-10-28 13:19:56
【问题描述】:

我无法播放 2 秒的小音频片段。我已经尝试过 stackOverflow 中提到的每个排列,类似于这个问题。没有什么对我有用,即使是似乎对其他人有用的解决方案。 我不知道是不是因为我没有可以测试的物理设备或其他原因。

我收到 Activity not found 错误:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.category.ACTION_VIEW dat=R.raw.song_name.mp3 }

我的音频播放代码:

Uri uri = Uri.parse("R.raw.song_name.mp3");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("audio/*");
intent.setData(uri);
startActivity(intent);

我的文件存储在:

res/raw/song_name.mp3

我没有在 AndroidManifest.xml 上做任何额外的事情。 我在模拟器上运行这个应用程序。这会导致这个错误吗?

【问题讨论】:

  • res/raw/song_name.mp3 。那不是“本地目录”。请先将 mp3 作为文件放在您设备上的某个位置。
  • 音频文件必须包含在我的 APK 中。 “本地目录”是指我不需要下载该文件。我可以简单地从资源目录访问。很抱歉造成混乱。

标签: android audio avaudioplayer audio-streaming


【解决方案1】:

您可以使用 MediaPlayer 类来代替 Intent。

MediaPlayer mp;
mp=MediaPlayer.create(getApplicationContext(),R.raw.song_name.mp3);
mp.start();

我希望这行得通。

【讨论】:

  • 不幸的是,意图是强制性的。我正在编写 Intent 章节。
  • 也许你可以这样做,但你为什么要这样做。您可以在 Mediaplayer 的帮助下轻松做到这一点。
【解决方案2】:

您的代码在广播和 媒体播放器

我建议您在此处阅读有关媒体播放器的信息 https://developer.android.com/reference/android/media/MediaPlayer.html

您可以在此处查看意图 https://developer.android.com/guide/components/broadcasts.html

//to play a local file you could do it this way 

 //create a new media player
        MediaPlayer mPlayer = new MediaPlayer();
//obtain the source
        try {
            mPlayer.setDataSource("path/to/youraudiofile.mp3");
        } catch (IOException e) {
            e.printStackTrace();
        }
//prepare the player
        try {
            mPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
//now start the player to begin playing the audio
        mPlayer.start();

【讨论】:

  • 其实我不必创建一个对象来处理播放器部分。我正在尝试通过意图将我的活动(播放音乐)委托给 android 的默认媒体播放器。我从来没有使用过这个功能,所以我在播放音频和视频部分时有点困惑。
  • 嗨,Biken,你好运吗?您是否能够通过意图完成播放音频文件?
猜你喜欢
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多