Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - how to make a button click play a sound file every time it been pressed?

Tags:

android

audio

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>
like image 516
4this Avatar asked Oct 19 '13 10:10

4this


4 Answers

  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:)

like image 157
Abhishek V Avatar answered Oct 21 '22 11:10

Abhishek V


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

like image 40
swisscoder Avatar answered Oct 21 '22 11:10

swisscoder


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);
    }
}
like image 28
Mukul Lakhwani Avatar answered Oct 21 '22 11:10

Mukul Lakhwani


I solved this like:

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

    if (sound.isPlaying()) {
        sound.seekTo(0);
        sound.start();
    }
}
like image 21
Hermetika Labs Avatar answered Oct 21 '22 11:10

Hermetika Labs