简体   繁体   English

Java Android:如何为媒体播放器提供资源的字符串值

[英]Java Android: How to give media player a string value to a resource

I have a function where i run an audio 我有一个运行音频的功能

public void PlaySound(String FileName){
     MediaPlr = MediaPlayer.create(Context, R.raw.s1);
     MediaPlr.start();
}

The problem is R.raw.s1 , i want to replace s1 with FileName , but it doesn't take a String. 问题是R.raw.s1 ,我想用FileName替换s1 ,但它不需要String。 What can i do??? 我能做什么???

Thanks for all help 感谢所有帮助

If the file is stored in the res/raw/ directory, you can retrieve its identifier through the following code: 如果文件存储在res/raw/目录中,则可以通过以下代码检索其标识符:

public void PlaySound(String fileName){
    int sound_id = context.getResources().getIdentifier(fileName, "raw",
                                                 context.getPackageName());
    if(sound_id != 0) {
      mediaPlr = MediaPlayer.create(context, sound_id);
      mediaPlr.start();
    }
}

I would also prefer to start variable names with small letters, rather than capital. 我还希望以小写字母开头的变量名,而不是大写字母。 This helps to distinguish from the static class. 这有助于区别静态类。

You can also create a map to store the ID for further reuse instead of retrieving the identifier each time. 您也可以创建一个映射来存储ID以供进一步使用,而不是每次都检索标识符。

Try this method.You can specify your string file path in mediaPlayer.setDataSource 尝试此方法。您可以在mediaPlayer.setDataSource指定字符串文件路径。

if(mMediaPlayer == null)
    mMediaPlayer    =   new MediaPlayer();
mMediaPlayer.reset();
try {
    mMediaPlayer.setDataSource(YourAudioFileLocation);
    mMediaPlayer.prepare();
} catch (IllegalArgumentException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
mMediaPlayer.start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM