user2494741
user2494741

Reputation:

how to add a sound file in android program

I want to write a program which can play a sound after clicking a button. I have written the code below:

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    MediaPlayer btnSound = MediaPlayer.create(this, R.raw.sound);
    Button button1 = (Button) findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            btnSound.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;
}

}

But I dont know where should I add this sound to my program I have created a new folder in res named raw and added sound to it but again this is an error in MediaPlayer btnSound = MediaPlayer.create(this, R.raw.sound); can any one please help me

thanks alot for your attention in advance

Upvotes: 3

Views: 2129

Answers (1)

user2511882
user2511882

Reputation: 9152

Try this

Button button1 = (Button) findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.sound);
    button1.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {
           mp.start();
        }
    });

Upvotes: 2

Related Questions