我制作了一个简单的音乐播放器应用程序,但它不播放SD卡中的音乐,当我用它来播放res / raw的歌曲时它正在工作

时间:2016-06-22 14:14:23

标签: java android android-mediaplayer

这是我的MainActivity代码。我只使用一项活动:

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;

    public class MainActivity extends AppCompatActivity implements      View.OnClickListener {

Button bPlay,bStop;
public static MediaPlayer mplayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bPlay=(Button)findViewById(R.id.button);
    bStop=(Button)findViewById(R.id.button2);
    bPlay.setOnClickListener(this);
    bStop.setOnClickListener(this);
}
@Override
public void onClick(View v){
    switch(v.getId()){
        case R.id.button:
            String path = "/sdcard/honey.mp3";
            //bStop.setText(path);
          // Uri myUri = Uri.parse("file:///storage/emulated/0/honey.mp3/");
           //Uri myUri = Uri.parse("android.resource://com.example.shubhamchauhan.mediaplayer/"+R.raw.honey);
            mplayer = new MediaPlayer();
            mplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try{
                mplayer.setDataSource(path);
            }catch(IllegalArgumentException e){
                Toast.makeText(getApplicationContext(),"You set wrong uri",Toast.LENGTH_SHORT).show();
            }catch(SecurityException e){
                Toast.makeText(getApplicationContext(),"You set wrong uri",Toast.LENGTH_SHORT).show();
            }catch(IllegalStateException e){
                Toast.makeText(getApplicationContext(),"You set wrong uri",Toast.LENGTH_SHORT).show();
            }catch(IOException e){
                Toast.makeText(getApplicationContext(),"You set wrong uri start",Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
            try {
                mplayer.prepare();
            }catch(IllegalStateException e){
                Toast.makeText(getApplicationContext(),"You set wrong uri",Toast.LENGTH_SHORT).show();
            }catch(IOException e){
                Toast.makeText(getApplicationContext(),"You set wrong uri prepare",Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
            mplayer.start();
            break;
        case R.id.button2:
            if(mplayer!=null && mplayer.isPlaying()){
                mplayer.stop();
            }
            break;
    }
}
}

如何解决?

0 个答案:

没有答案