15

I have open a new project -

Now what I would like to do is this - By pressing on the button I want an mp3 file being played - and also that each time the button is pressed than the sound file will start playing from the start of it once again - so let's say that the mp3 is 10 sec long, and I pressed the button and it's playing and after 4 sec I pressed the button again than the sound will be played again.

Now what I would like to know is- 1- Where should I put the mp3 file?

2-what code do I have to add in order that when the button is pressed than the mp3 file will be played (let's call the mp3 file click_sound.mp3)?

3- What I need to add to the code in order that the sound will be played again each time I will pressed the button?

This is the code of the MainActivity.java -

package com.example.test1;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

and this is the activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/play" />

</RelativeLayout>
BenMorel
  • 34,448
  • 50
  • 182
  • 322
4this
  • 759
  • 4
  • 13
  • 27
  • Shame someone decided to take down my rating- only trying to understand something - why to punished someone just because he doesn't understand something?! – 4this Oct 19 '13 at 10:46
  • 1
    you have hundreds of examples of this and you should not be lazy to search for it over a Internet. Good start is here: http://developer.android.com/reference/android/media/MediaPlayer.html – androidEnthusiast Nov 10 '13 at 14:38
  • Check Chris's answer at : "http://stackoverflow.com/questions/3369068/android-play-sound-on-button-click-null-pointer-exception" . Hope it helps – Basher51 Jul 13 '14 at 07:01

5 Answers5

37
  1. You should put mp3 file in /assets folder.

  2. put this code inside onCreate() method after setContentView()

    final MediaPlayer mp = new MediaPlayer();
    Button b = (Button) findViewById(R.id.button1); 
    
    b.setOnClickListener(new OnClickListener() {
    
        @Override
        public void onClick(View v) {
    
            if(mp.isPlaying())
            {  
                mp.stop();
            } 
    
            try {
                mp.reset();
                AssetFileDescriptor afd;
                afd = getAssets().openFd("AudioFile.mp3");
                mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
                mp.prepare();
                mp.start();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
    
    
        }
    });
    

    3.sound will be played again each time you press button. You don't have to write any extra code for that.

Note that AudioFile.mp3 is the name of the mp3 file in /assets folder

Hope this answer is helpful:)

Tatarize
  • 10,238
  • 4
  • 58
  • 64
Abhishek V
  • 12,488
  • 6
  • 51
  • 63
  • from some reason the setOnClickListener AND OnClickListener() and also onClick(View v) - are all errors - any idea why? – 4this Oct 19 '13 at 10:33
  • Click on that red color error symbol.It will give you suggestions. Choose `Import OnClickListener` in that list. Or else place cursor on `b.setOnClickListener(new OnClickListener()` line and press `ctrl+1` in windows,linux or `cmd+1` in mac. It will give you suggestions. Choose `Import OnClickListener` in that list. – Abhishek V Oct 19 '13 at 10:37
  • Well first of all, thank you that really works. But it seems like when i pressing on the button for a secoend time - the sound don't stops, it simply playing the file again while the first play of the sound is still on - are you sure there's no need to add something to the code? – 4this Oct 19 '13 at 10:44
  • Have edited the code...now it stops the sound if the sound is playing when you press the button again. Check if this works:) – Abhishek V Oct 19 '13 at 12:29
  • Well it shows me that all the mp are an error (not including the first mp in the new MediaPlayer) - so the advice it gave me was to add final to the MediaPlayer mp = new MediaPlayer(); line - that's what i have done - all the error are gone - but when i tried the code - on the first click i have heard the sound, but by secoend click the sound stoped- but after it any other clicking on the button will not play the sound. – 4this Oct 19 '13 at 12:58
  • Again what i'm wat to do is - if let's say the mp3 length is 10sec - so when i pressing on the button the sound starting - and let's say afer 4 sec i wnat to click on the button again - then what i want to happen is that the sound will satrt from the 0 sec and play itslef again - so to sum it up what iwant to button will do is by each click the sound will start playing over again – 4this Oct 19 '13 at 13:11
  • The bug is the mp.reset() it should be called outside of the if statement. Do that and all the problems will vanish. – Tatarize Feb 17 '15 at 10:44
  • Check the state diagram: http://stackoverflow.com/questions/7816551/java-lang-illegalstateexception-what-does-it-mean PlaybackComplete is not .isPlaying() but cannot be used to set the media. You must reset to set a new media source. And you don't with that if statement, you only reset when it's playing. You'll get a State 128 error. Just always reset() and you'll be fine. Idle -> Idle will throw no error. – Tatarize Feb 17 '15 at 10:53
  • Thanks. Works also perfectly with .m4a sound files. If you want to reuse the player "mp", with multiple sounds, make it static and not final : then when you press the same button again while it is playing a sound, this stops the current sound before playing the next one. – Chrysotribax May 12 '17 at 08:21
2

If you really have to invoke the click programmatically because the view has no own sound, i would solve it like that, its the simplest solution and a oneliner

view.playSoundEffect(SoundEffectConstants.CLICK);

very simple and works, if you want to make a layout play a sound you need to put

android:soundEffectsEnabled="true"

to the Layout

swisscoder
  • 129
  • 2
  • 11
1

I think this is the pretty much what you wanted:

public class MainActivity extends Activity {
    String tag;
    static MediaPlayer mp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tag=getPackageName();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mp = new MediaPlayer();
        Button b = (Button) findViewById(R.id.button1); 

         b.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                   // MediaPlayer mp = new MediaPlayer();

                    if(!mp.isPlaying())
                    {
                        mp= new MediaPlayer();
                    }
                    try {
                        AssetFileDescriptor afd = getAssets().openFd("AudioFile.mp3");
                        mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
                        mp.prepare();
                        mp.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });

        /*b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if(mp.isPlaying())
                {  
                    Log.e(tag,"mp is playing");

                    mp.stop();
                    mp.reset();
                    //mp.start();
                } 
                try {

                    AssetFileDescriptor afd;
                    afd = getAssets().openFd("AudioFile.mp3");
                    mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
                    mp.prepare();
                    mp.start();
                  //  mp.release();
                } catch (IllegalStateException e) {
                    Log.e(tag, e.toString());
                    //e.printStackTrace();
                } catch (IOException e) {
                    Log.e(tag, e.toString());

                    //e.printStackTrace();
                }



            }
        });

        mp.setOnPreparedListener(new OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                // TODO Auto-generated method stub
            mp.start(); 
            }
        });*/

    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Mukul Lakhwani
  • 89
  • 1
  • 1
  • 6
  • See my comment on the above post. The correct answer to it throwing an error is to figure out why. Not obliterate the object because of a lack of understanding. The problem with the original code is that mp.reset() must be called while in State 128 (PlaybackComplete), to get to state Idle but you cannot get there with that code because PlaybackComplete is not isPlaying() – Tatarize Feb 18 '15 at 12:06
1

I solved this like:

public void onClick(View v) {
    sound.start();

    if (sound.isPlaying()) {
        sound.seekTo(0);
        sound.start();
    }
}
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
0

Hope this steps will help you to go ahead..

1.put your mp3 file under row folder (if not exist create one --> Right click on project ->new -> createfolder)

2.R&D ongoogle to play mp3 first (media player)

3.on click of button load that perticular file (by setting onclick listner to button)

best luck

Kalpesh Lakhani
  • 1,003
  • 14
  • 28
  • what do you mean in R&D ongooogle to play mp3 first? – 4this Oct 19 '13 at 10:23
  • talking about some search on google..here i done for you..check these 1)http://intransitione.com/blog/playing-an-audio-file-with-android/ 2)http://stackoverflow.com/a/5466930/1199602 – Kalpesh Lakhani Oct 19 '13 at 10:28