如何使用媒体播放器的意图



我想在我的家庭作业应用程序中使用 Intention。当我单击按钮 1 时,我的声音活动打开,播放声音 1.mp3 文件。但是当我点击按钮2,声音2.mp3在SoundActivity中播放的文件时,我想这样做。

这是我的主要活动.java代码:

button1=findViewById(R.id.button1);
button2=findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            Intent intent = new Intent(this, SoundActivity.class);
            }
        });
button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            Intent intent = new Intent(this, SoundActivity.class);
            }
        });

这是我的声音活动方面:

sound1 = MediaPlayer.create(this, R.raw.bell);
sound2 = MediaPlayer.create(this, R.raw.siren);
sound1.start();
'Another way is that you just pass a key like which song you want to play on button click listener like'


button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            Intent intent = new Intent(this, SoundActivity.class);
            intent.putExtra("SOUND", "sound1");
            startActivity(intent);
            }
        });
button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            Intent intent = new Intent(this, SoundActivity.class);
            intent.putExtra("SOUND", "sound2");
            startActivity(intent);
            }
        });



'get this key in sound activity and pass the sound on the basis of condition like'



Bundle bundle = getIntent().getExtras();
        String sound = bundle.getInt("SOUND");
if(sound.equals(sound1)){
play_sound = MediaPlayer.create(this, R.raw.bell);
}else if(sound.equals(sound2)){
play_sound = MediaPlayer.create(this, R.raw.siren);
}
play_sound.start();


'Hope you get the best'
'You can send your sound with intent using putt extras like'
button1=findViewById(R.id.button1);
button2=findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            Intent intent = new Intent(this, SoundActivity.class);
            intent.putExtra("SOUND", R.raw.bell);
            startActivity(intent);
            }
        });
button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            Intent intent = new Intent(this, SoundActivity.class);
            intent.putExtra("SOUND", R.raw.siren);
            startActivity(intent);
            }
        });
'in sound actvity you just get the sound using bundle and pass it to media player like'
Bundle bundle = getIntent().getExtras();
        int sound = bundle.getInt("SOUND");
sound1 = MediaPlayer.create(this, sound);
sound1.start();


'Hope you get the solution.'

最新更新