如何在android中播放手机内部存储器中的音频文件

如何在android中播放手机内部存储器中的音频文件,android,Android,我想播放手机内存中的歌曲(即没有sd卡) 在媒体文件的音乐文件中 String fileName = "1.mp3"; String completePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/"+ fileName; File file = new File(completePath); Uri myUri1 = Uri.fromFile(file); fin

我想播放手机内存中的歌曲(即没有sd卡) 在媒体文件的音乐文件中

String fileName = "1.mp3";
String completePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/"+ fileName;
 File file = new File(completePath); 
 Uri myUri1 = Uri.fromFile(file);
 final MediaPlayer 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 2.3.3),从内部存储器播放音频会导致错误。这是因为MediaPlayer被视为第三方应用程序,并且没有访问应用程序内部存储的权限

这里是播放音频文件的一个简单示例

尝试以下代码:

String path = "/mnt/sdcard/"
MediaPlayer mPlayer = new MediaPlayer();    
try {
mPlayer.setDataSource(path+"/audio/sound.mp3"); 
mPlayer.prepare();                              
} catch (IllegalArgumentException e) {
    e.printStackTrace();
}     
mPlayer.start();
*确保在/mnt/sdcard/audio/

不要忘记在AndroidManifest.xml中提供以下权限

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

使用以下代码从外部存储器获取文件(音频)并播放音乐

String path = Environment.getExternalStorage + "/"+ fileName+".mp3";
MediaPlayer player = new MediaPlayer();  

try {
   player.setDataSource(path); 
   player.prepare();                              
} catch (IllegalArgumentException e) {
   e.printStackTrace();
} catch (Exception e) {
  System.out.println("Exception of type : " + e.toString());
  e.printStackTrace();
}

player.start();
别忘了放许可证

android.permission.READ_EXTERNAL_STORAGE

使用此代码加载音乐

 private void loadAudio() {
    ContentResolver contentResolver = getContentResolver();
    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
    String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
    Cursor cursor = contentResolver.query(uri, null,selection, null, sortOrder);
    if (cursor != null && cursor.getCount() > 0) {
        audioList = new ArrayList<> ();
        while (cursor.moveToNext()) {
            String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));

            // Save to audioList
            audioList.add(new Audio(data, title, album, artist));
        }
    }
    cursor.close();
}
确保您有音频类并将其放入清单中

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

您可以这样做(kotlin:)

在舱单中:

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

Dexter依赖项:)


Uzeeta,你有任何错误吗?先将代码放入代码块中格式化代码。在你的问题中,你想从内部存储读取文件,但如果你使用
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY\u MUSIC)
你只需尝试从外部存储读取即可。否,程序中没有错误,但toast显示消息“您可能未正确设置URI!”,请建议解决方案。
 //fetch the audio files from storage
val contentResolver = this.contentResolver
val uri: Uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val cursor: Cursor? = contentResolver?.query(uri, null, null, null, null)

//looping through all rows and adding to list
if (cursor != null && cursor.moveToFirst()) {
    do {
        val title: String = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE))
        val artist: String = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST))
        val duration: String = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION))
        val url: String = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
        val modelAudio = ModelAudio()
        modelAudio.setaudioTitle(title)
        modelAudio.setaudioArtist(artist)
        modelAudio.setaudioUri(url)
        modelAudio.setaudioDuration(duration)
        audioArrayList.add(modelAudio)
    } while (cursor.moveToNext())
}
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 private fun checkPermissions() {
 Dexter.withActivity(this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
        .withListener(object : PermissionListener {
            override fun onPermissionGranted(permissionGrantedResponse: PermissionGrantedResponse) {
            }
            override fun onPermissionDenied(permissionDeniedResponse: PermissionDeniedResponse) {}
            override fun onPermissionRationaleShouldBeShown(
                    permissionRequest: PermissionRequest,
                    permissionToken: PermissionToken
            ) {
                // asking for permission
                permissionToken.continuePermissionRequest()
            }
        }).check()
 implementation 'com.karumi:dexter:6.2.2'