OK I'm new to android dev's and Java so I'm having problems with on click method here's my code Ii know I've gotta be close thanks in advance all I want my button to do is when its clicked on the phone play a sound. But I get this error, pistol1 cannot be resolved or not in a field, it's a sound file that I want to play when I click on button.
import android.os.Bundle;
import android.app.Activity;
import android.media.MediaPlayer;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button one = (Button)this.findViewById(R.id.imageButton1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.pistol1);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
}
}
Are you sure your file is inside a folder called raw inside res folder ?
If so, did you made the good import ?
import my.project.name.R
or
import my.project.name.R.raw
As documentation is saying: Android doc.
Here is an example of how to play audio that's available as a local raw resource (saved in your application's res/raw/ directory):
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
mediaPlayer.start(); // no need to call prepare(); create() does that for you
In this case, a "raw" resource is a file that the system does not try to parse in any particular way. However, the content of this resource should not be raw audio. It should be a properly encoded and formatted media file in one of the supported formats.
Also you should look over the: Supported Media Formats
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.