Android select mp3 file

前端 未结 3 2175
故里飘歌
故里飘歌 2020-12-29 11:06

Sorry if this has already been answered, but I can\'t specify my question very well. I have an activity that needs a song file from your device, and I want it when I press a

3条回答
  •  滥情空心
    2020-12-29 11:28

    To open file explorer, requestCode is just an integer so for sake , pass 1

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("audio/*"); // specify "audio/mp3" to filter only mp3 files
    startActivityForResult(intent,1);
    

    Setup Media Player,

    MediaPlayer player = new MediaPlayer();
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    

    Fetch result file from explorer,

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
     /*check whether you're working on correct request using requestCode , In this case 1*/
    
        if(requestCode == 1 && resultCode == Activity.RESULT_OK){
            audio = data.getData(); //declared above Uri audio;
            Log.d("media", "onActivityResult: "+audio);
        }
    
        super.onActivityResult(requestCode, resultCode, data);
    }
    

    Start Playing audio,

     player.setDataSource(new FileInputStream(new File(audio.getPath())).getFD());
    
     player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        player.start();
                    }
                });
    
     player.prepareAsync();
    

    To stop audio,

     if(player.isPlaying())
                player.stop();
    

    Finally, Add permission in manifest to read external files,

     
    

    Add your controller widgets and play with MediaPlayer methods to create customized Mp3 player ;)

提交回复
热议问题