I've tried many different ways, but none of them seem to work. This method gets no errors, but does nothing. I'm placing all of my sounds in a subdir under my main project. Most of the code I've tried was different ways like the MediaPlayer and SoundPooling. None of them worked for me and so I tried this. If anyone could correct this for me or get me to a tutorial, that would be great.
package me.javoris767.twds2soundboard;
import java.io.IOException;
import me.javoris767.twds2soundboard.R;
import android.view.View;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
public class ClementinePage extends Activity {
MediaPlayer mp=new MediaPlayer();
public boolean isPlaying;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_clementine_page);
}
public void playSound(String file) {
AssetFileDescriptor afd = null;
try {
afd = getAssets().openFd(file);
MediaPlayer player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
afd.getLength());
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer p1) {
p1.start();
isPlaying = true;
}
});
}catch (IOException e) {
e.printStackTrace();
}
}
public void onNoClick(View v) {
playSound("sounds/ohno.mp3");
}
}
Do something like this
//initialising the two new buttons
final Button btSong1 = (Button)findViewById(R.id.btnPlaySong1);
final Button btSong2 = (Button)findViewById(R.id.btnPlaySong2);
//initialising the two new media player instances
song1 = new MediaPlayer();
song1 = MediaPlayer.create(this, R.raw.song3);
song2 = new MediaPlayer();
song2 = MediaPlayer.create(this, R.raw.song4);
//The code for the two buttons go here
btSong1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
switch(stateOfPlaying){
case 0:
song1.start();
stateOfPlaying = 1;
btSong1.setText("Pause Song 1");
btSong2.setVisibility(View.INVISIBLE);
break;
case 1:
song1.pause();
stateOfPlaying = 0;
btSong1.setText("Play Song 1");
btSong2.setVisibility(View.VISIBLE);
break;
}//switch
}//end of onClick
});//btSong1
btSong2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
switch(stateOfPlaying){
case 0:
song2.start();
stateOfPlaying = 1;
btSong2.setText("Pause Song 2");
btSong1.setVisibility(View.INVISIBLE);
break;
case 1:
song2.pause();
stateOfPlaying = 0;
btSong2.setText("Play Song 2");
btSong1.setVisibility(View.VISIBLE);
break;
}//switch
}//end of onClick
});//btSong2
I'd advise against using MP3 files in Android because it seems to be handling OGG ones much better. Can you do this?
Related
hello I use MediaPlayer for play sound in my project in android studio
when I click in a button and play sound , and when I click in another button that button play another sound , I want the first sound or another sound be stoped and just the last button that I clicked be played
I try this code but it not worked
package azad.broooska.fartfuns;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MusicFartActivity extends AppCompatActivity implements View.OnClickListener {
private CardView cardView1, cardView2, cardView3, cardView4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_fart);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
cardView1 = findViewById(R.id.card_music1);
cardView2 = findViewById(R.id.card_music2);
cardView3 = findViewById(R.id.card_music3);
cardView4 = findViewById(R.id.card_music4);
cardView1.setOnClickListener(this);
cardView2.setOnClickListener(this);
cardView3.setOnClickListener(this);
cardView4.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int id = view.getId();
final MediaPlayer s1 = MediaPlayer.create(this, R.raw.bohemian_fartsody);
final MediaPlayer s2 = MediaPlayer.create(this, R.raw.fart_ballade);
final MediaPlayer s3 = MediaPlayer.create(this, R.raw.fart_uverture);
final MediaPlayer s4 = MediaPlayer.create(this, R.raw.farting_xmas);
if (id == R.id.card_music1) {
s1.start();
s2.stop();
s3.stop();
s4.stop();
} else if (id == R.id.card_music2) {
s2.start();
s1.stop();
s3.stop();
s4.stop();
} else if (id == R.id.card_music3) {
s3.start();
s2.stop();
s1.stop();
s4.stop();
} else {
Toast.makeText(this, "noThing", Toast.LENGTH_SHORT).show();
}
}
}
you are creating new instances of MediaPlayer each time something is clicked and assigning the variables to new objects; make s1,s2... class property;
MediaPlayer s1 ,s2,s3,s4;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_fart);
//some code
s1 = MediaPlayer.create(this, R.raw.bohemian_fartsody);
//assign the rest;
}
public void onClick(View view) {
int id = view.getId();
if (id == R.id.card_music1) {
s1.start();
s2.stop();
s3.stop();
s4.stop();
}
//rest of the code
}
Well, its seems like you don`t want to play very long sounds because you have names like
"fart_ballade" and "fart_uverture" in your code.
If your sounds are not very long it is better to work with the SoundPool class.
The MediaPlayer class sometimes can cause problems if you switch fast between sounds.
So if your sounds are not that long, you can try the SoundPool class.
Here you can learn more about the SoundPool class:
How to use SoundPool
I won`t write any code because SoundPool needs more than 5-6 lines of code to work properly.
EDIT: Realized and solved the problem on my own. Thank you.
Please bear with me it's actually my first time using Android Studio and Stackoverflow. What I am trying to make is a music player, there are 2 activities. In the second activity when the user taps the play button, the music plays. If the user backs, the music will stop playing and go back to the first activity. Somehow on back pressed is not working. It's grayed out and it tells me that the Method is never used.
package com.radiantminds.radiantminds;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class player1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
}
#Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
}
You have to put it on an Activity, don't forget to call #Override
#Override
public void onBackPressed()
{
super.onBackPressed(); //if you want to do something new remove this line
}
The problem is that you have to place the onBackPressedMethod() outside, as follows :
public class player1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
#Override
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
//if you want to do the back action aswell, uncomment the following line
//super.onBackPressed();
}
Make sure the #override is there above the method and you don't declare the method twice.
other alternative is:
onKeyDown()
or add:
super.onBackPressed();
in the method onBackPressed (though i dont suggest it really)
So I'm making this Star Wars fan app on Android.
I've got this image of Yoda and a button for him. When you tap it, now he says a sentence (with the mediaplayer).
The thing is, I want him to say different things so I got 4 different MP3 files,but how do I let it choose randomly which one to play when the user clicks on the button?
This is my code for now:
package be.ehb.arnojansens.simpleFrag;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import be.ehb.arnojansens.fragmentexampleii.R;
public class SimpleFragmentActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_fragment);
final Button advice = (Button) findViewById(R.id.YodaAdvice);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.yodamessage);
advice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Hmm Busy I Am", Toast.LENGTH_LONG).show();
mp.start();
}
});
}
}
You can have 4 final messages
final MediaPlayer mp = MediaPlayer.create(this, R.raw.yodamessage);
final MediaPlayer mp1 = MediaPlayer.create(this, R.raw.yodamessage1);//File names would be different I guess
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.yodamessage2);
final MediaPlayer mp3 = MediaPlayer.create(this, R.raw.yodamessage3);
Also you need a random
Random random=new Random();
And then in your on click method
int r = random.nextInt(4);
if(r==0){
mp.start();
Toast.makeText(getApplicationContext(), "Hmm Busy I Am", Toast.LENGTH_LONG).show();
}
if(r==1){
mp1.start();
Toast.makeText(getApplicationContext(), "I'm hungry", Toast.LENGTH_LONG).show();
}
if(r==2){
mp2.start();
Toast.makeText(getApplicationContext(), "My droid now", Toast.LENGTH_LONG).show();
}
if(r==3){
mp3.start();
Toast.makeText(getApplicationContext(), "Not droid you are looking for", Toast.LENGTH_LONG).show();
}
When I press a button it plays the sound fine but when I click it again nothing happens.
I want it to repeat the sound each time its clicked? Any ideas??
Thanks for looking. :-)
package com.example.sherlock;
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Conent extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
final MediaPlayer mp = new MediaPlayer();
Button b = (Button) findViewById(R.id.button1);
final MediaPlayer mp1 = new MediaPlayer();
Button c = (Button) findViewById(R.id.Button2);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
mp.reset();
}
try {
AssetFileDescriptor afd;
afd = getAssets().openFd("s1.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
c.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(mp1.isPlaying())
{
mp1.stop();
mp1.reset();
}
try {
AssetFileDescriptor afd;
afd = getAssets().openFd("s2.mp3");
mp1.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp1.prepare();
mp1.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
private SoundPool sp;
private int music;
sp= new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);//the first param is times of play music at the same time
music = sp.load(this, R.raw.start, 1);//start is source music
mButton01.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
sp.play(music, 1, 1, 0, 0, 1);
}
}
maybe you can change your *.mp3 to *.ogg.
Lets say that MediaPlayer "doesn't like" to be interupted while playing, what can be a case in your example if you click buttons while sounds are playing.
I think you can cut .reset() method from its place and paste it right before setDataSource in your try bloc:
mp.reset();
mp.setDataSource(MEDIA_PATH);
mp.prepare();
mp.start();
It could possibly solve your problem, but have in mind that both reset() and prepare() are async methods so relying on MediaPlayer being responsive enough to handle them in your usecase is probably okay, but not a good practice.
Instead of using MediaPlayer, I would use SoundPool in your case. It seems that you aren't going to play long sounds (music or so), and your sounds can overlap. For this case, SoundPool is way way more reliable and faster.
I also found similar thread on stack overflow, hope it will help you a bit - How to Play sound when button is clicked in Android?, see Jan S answer.
Don't reset your mp instead setup a mp.oncompletelistener and inside
public void onCompletion(MediaPlayer mp) {
//set the datasource again}
All you have to do is place these under your, if Button clicked event
try{
mp.start();
}
catch(Exception e){}
}
and
try{
mp1.start();
}
catch(Exception e){}
}
I have a button in an activity and when i press it the sound plays. The sound itself is 2 seconds long. And it only plays when i press on the button. I wanna make it that a user can hold down the button and the sound plays till he releases the button. How can i do this? Here's my current code.
package android.app;
import android.app.R;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class activity2 extends Activity{
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
//back button that takes u to main.xml
Button next = (Button) findViewById(R.id.Back);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
} );
//Button that plays sound (whippingsound)
Button sound = (Button) findViewById(R.id.sound);
sound.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(activity2.this, R.raw.whippingsound);
mp.start();
}
} );
}
}
Thanks!!!
The solution to your problem is a combination of
Triggering event when Button is pressed down in Android
and
play sound while button is pressed -android.
Namely, you're using an onClickListener instead of onTouchListener.
Try this instead (note: I also moved the media player out so you create it once and use it over and over again).
public class activity2 extends Activity{
MediaPlayer mp = null;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
//back button that takes u to main.xml
Button next = (Button) findViewById(R.id.Back);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
} );
mp = MediaPlayer.create(activity2.this, R.raw.whippingsound);
//Button that plays sound (whippingsound)
Button sound = (Button) findViewById(R.id.sound);
sound.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mp.setLooping(true);
mp.start();
break;
case MotionEvent.ACTION_UP:
mp.pause();
break;
}
return true;
}
});
}