android - 如何在Android中播放手机内存中的音频文件

标签 android

我想制作示例在android中播放音频文件,我想播放手机内存中的音乐。请建议如何给出路径。

我正在写这篇文章,但面临 java.io.IOException:prepare failed 错误

 final MediaPlayer mp = new MediaPlayer();
 try{ 
      mp.setDataSource(Environment.getRootDirectory()+"/1.mp3");
      mp.prepare();
   }
   catch(Exception e)
   {
     e.printStackTrace();
   }

最佳答案

你可以尝试这样的事情。

// Add permission to your menifest to Read File from your storage


<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

然后在您调用加载 mp3 文件的 JAVA 类/Activity 中。

MediaPlayer mPlayer;

        // Your Media Player will be called with Audio file here..
          private void loadAudio(){

            String fileName = "YourAudio.mp3";
            String completePath = Environment.getExternalStorageDirectory() + "/" + fileName;

            File file = new File(completePath); 

                 Uri myUri1 = Uri.fromFile(file);
                    mPlayer = new MediaPlayer();
                    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    try {
                        mPlayer.setDataSource(getApplicationContext(), myUri1);
                    } catch (IllegalArgumentException e) {
                        Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                    } catch (SecurityException e) {
                        Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                    } catch (IllegalStateException e) {
                        Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mPlayer.prepare();
                    } catch (IllegalStateException e) {
                        Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                    } catch (IOException e) {
                        Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                    }
                    mPlayer.start();
            }

希望这对您有帮助。

关于android - 如何在Android中播放手机内存中的音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30100083/

相关文章:

android - 每次方向改变时,Phonegap Android 应用程序都会重置到主屏幕

android - 在android中以慢动作播放视频

android - Android 中的两条腿 Oauth

android - 使用 Google +/PlusClient 获取个人信息

android - 我应该如何在 android 上保存包含 ListView 的 fragment 状态?

android - java.lang.NumberFormatException : Invalid int: "" in android 异常

android - 在 Core 2 Duo 10.11.6 Mac OS 上运行 Android Studio 模拟器

java - 无法创建 WifiConfiguration

javascript - 为什么上传明显成功时上传的音频会损坏?

android - 在 Android 中启用禁用蓝牙