简体   繁体   中英

Android Studio Share mp3 and play/stop songs

I have this code:

import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;

public class MainActivity extends AppCompatActivity {
MediaPlayer mp;

//Buttons 
ImageButton peroperoperopero;
ImageButton personajitosdos;
peroperoperopero = (ImageButton) findViewById(R.id.peroperoperopero);
personajitosdos = (ImageButton) findViewById(R.id.personajitosdos);

//code
peroperoperopero.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mp = MediaPlayer.create(MainActivity.this,R.raw.peroperopero);
            mp.start();
        }
    });

peroperoperopero.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Intent compartirAudio = new Intent(android.content.Intent.ACTION_SEND);
            compartirAudio.setType("audio/*");
            compartirAudio.putExtra(Intent.EXTRA_STREAM,
                    Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/raw/" + R.raw.peroperopero));
            startActivity(Intent.createChooser(compartirAudio, "Compartir vía"));
            return false;
        }
    });

personajitosdos.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mp = MediaPlayer.create(MainActivity.this,R.raw.unospersonajitos);
            mp.start();
        }
    });

}

}

I would need to know what to modify to:

  • Pressing the button peroperoperopero share it in WhatsApp (currently when I share it, a document is sent but not the audio)

  • I want only one sound to play at the same time, now if I precede the two buttons at the same time the sounds are superimposed.

  • I also want that while the sound is playing, if I press the button again, it stops.

please tell me what do I have to change in the code? Thank you very much.

For audio play and stop use this following:

  MediaPlayer mp;
  mp = MediaPlayer.create(context, R.raw.sound_one);
  mp.setOnCompletionListener(new OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
    // TODO Auto-generated method stub
    mp.reset();
    mp.release();
    mp=null;
   }
  });
  mp.start();

To share audio with what's app you can go to the following link Sharing audio file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM