Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importing a raw mp3 resource for mediaplayer

I am trying to play a simple mp3 file with the following code:

package swalehm.android.examples.myTest1;
import swalehm.android.examples.myTest1.R;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.TextView;

public class myTest1Main extends Activity 
{
    Context context;

   public MediaPlayer mp = MediaPlayer.create(this, R.raw.sound1);

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        tv.setText("Hello, Android");
        setContentView(tv);
        mp.start();
    }
}

I have added a folder named 'raw' in the 'res' folder and the file sound1.mp3 is in it.

I checked R.java. The named resource sound1 does exist in that file. However, when I build it, I get an error saying sound1 cannot be resolved or is not a field. I went through the forum and saw a suggestion to remove android.R from the imprts. now i get a error saying:

The method MediaPlayer(myTest1Main, int) is undefined for the type myTest1Main.

like image 630
Swalehm Avatar asked Dec 28 '25 03:12

Swalehm


1 Answers

It should be:

public MediaPlayer mp = MediaPlayer.create(this, R.raw.sound1);
like image 78
Rajath Avatar answered Dec 30 '25 18:12

Rajath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!