Android MediaPlayer:基于URI原始播放音频资源 [英] Android MediaPlayer: Play Audio Resource in Raw Based on URI

查看:114
本文介绍了Android MediaPlayer:基于URI原始播放音频资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要解决的问题是需要回放音频文件的活动.大多数文件将由用户创建(并保存到外部存储),因此将使用以下代码(基于Google的示例代码)播放:

The problem I am trying to solve is in an activity that needs to play back audio files. Most of the files will be user created (and saved into external storage), and therefore played with the following code (based on Google's example code):

MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setDataSource(filename);
mPlayer.prepare();
mPlayer.start();

不过,某些音频文件将包含在应用程序中,通常使用以下代码播放:

Some of the audio files, though, are going to be included with the app, are usually played with the following code:

MediaPlayer mPlayer = MediaPlayer.create(getBaseContext(), R.raw.filename);
mPlayer.prepare();
mPlayer.start();

问题是我希望能够像播放用户创建的文件一样播放原始文件夹中的音频文件,因为我不一定知道需要哪个.我尝试尝试获取原始文件夹中音频文件的URI并使用以下代码播放它:

The issue is that I would like to be able to play the audio files in the raw folder in the same way that I am playing the user created files since I don't necessarily know which will be needed. I tried tried to get the URI of the audio file in the raw folder and play it with the following code:

Uri uri = Uri.parse("android/resource://com.my.package/" + R.raw.filename);
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setDataSource(uri.toString());
mPlayer.prepare();
mPlayer.start();

但是什么也没发生.没有错误消息,没有播放音频.

But nothing happens. No error messages, no playing audio.

我概述了我认为是最简单的解决方案,但是如果它能够完成任务,我愿意走另一条路.非常感谢您的协助.

I outlined what I thought was the simplest solution, but I am willing to go another route if it accomplishes the task. Any assistance is greatly appreciated.

推荐答案

我设法使其正常运行,这是我使用的代码.

I've managed to get it working, here is the code I used.

mMediaPlayer = new MediaPlayer();
Uri mediaPath = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.filename);
try {
    mMediaPlayer.setDataSource(getApplicationContext(), mediaPath);
    mMediaPlayer.prepare();
    mMediaPlayer.start();
} catch (Exception e) {
    e.printStackTrace();
}

我在您的代码中看到了两个问题.首先是"android/resource"需要变成"android.resource"

I see two problems I see with your code. The first is that "android/resource" needs to become "android.resource"

第二个原因是setDataSource(String)在这种情况下不起作用,因为您需要上下文来使用原始文件,否则它将尝试错误地打开文件.(请参见 MediaPlayer.setDataSource(String)不适用于本地文件)

The second is that setDataSource(String) won't work in this case due to the fact that you need context to use raw files as otherwise it tries to open the file incorrectly. (See the top answer in MediaPlayer.setDataSource(String) not working with local files)

这篇关于Android MediaPlayer:基于URI原始播放音频资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆