0

I'm trying to make a simple media player with a play and stop button. But I'm getting an error in:
method MediaPlayer.create(Context, int)is not applicable,
method MediaPlayer.create(Context, Uri, SurfaceHolder) is not applicable,
method MediaPlayer.create(Context, Uri) is not applicable.

I have looked at a few post on StakeOverflow but none of them seem to have helped. Can anyone enlighten me?

Here are a few that I have found:

Context not recognisied:Method not applicable for arguments

Can't use MediaPlayer.create in new View.OnFocusChangeListener() in Android app

public class MainFragment extends Fragment {

private MediaPlayer mediaPlayer;
public TextView songName, duration;
private double timeElapsed = 0, finalTime = 0;
private Handler durationHandler = new Handler();
private SeekBar seekbar;

public MainFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //initialize views
    initializeViews();
}

public void initializeViews() {
    songName = (TextView) getView().findViewById(R.id.songName);
    mediaPlayer = MediaPlayer.create(this, R.raw.no_diggity);
    finalTime = mediaPlayer.getDuration();
    duration = (TextView) getView().findViewById(R.id.songDuration);
    seekbar = (SeekBar) getView().findViewById(R.id.seekBar);
    //songName.setText("Sample_Song.mp3");

    seekbar.setMax((int) finalTime);
    seekbar.setClickable(false);
}

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    return rootView;
}

// play mp3 song
public void play(View view) {
    mediaPlayer.start();
    timeElapsed = mediaPlayer.getCurrentPosition();
    seekbar.setProgress((int) timeElapsed);
    durationHandler.postDelayed(updateSeekBarTime, 100);
}

//handler to change seekBarTime
private Runnable updateSeekBarTime = new Runnable() {
    public void run() {
        //get current position
        timeElapsed = mediaPlayer.getCurrentPosition();
        //set seekbar progress
        seekbar.setProgress((int) timeElapsed);
        //set time remaing
        double timeRemaining = finalTime - timeElapsed;
        duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));

        //repeat yourself that again in 100 miliseconds
        durationHandler.postDelayed(this, 100);
    }
};
}
Community
  • 1
  • 1

3 Answers3

0

You are passing the fragment as Context, pass the activity instead:

mediaPlayer = MediaPlayer.create(this.getActivity(), R.raw.no_diggity);

Then don't use onCreate method, put your initializeViews(); call in the onCreateView() method after load the view and before returning it

@Override
public View onCreateView(LayoutInflater inflater,
                     ViewGroup container,
                     Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    initializeViews();
    return rootView;
}

EDIT try something like this, I'm just throwing code right here with copy/paste of your code, it could not work, its just an idea of how things should work:

 public void initializeViews(View view) {
    //HERE YOU GET THE INSTANCES OF THE VIEWS IN THE LAYOUT
    songName = (TextView)view.findViewById(R.id.songName);
    mediaPlayer = MediaPlayer.create(this.getActivity(), R.raw.no_diggity);
    finalTime = mediaPlayer.getDuration();
    duration = (TextView)view.findViewById(R.id.songDuration);
    seekbar = (SeekBar)view.findViewById(R.id.seekBar);
    //songName.setText("Sample_Song.mp3");

    seekbar.setMax((int) finalTime);
    seekbar.setClickable(false);
}

@Override
public View onCreateView(LayoutInflater inflater,
                     ViewGroup container,
                     Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    initializeViews(rootView)

    return rootView;
}

My advice is that you look for some example of code of how to use fragments first because you are missing some basics and after a working example of the use of a MediaPlayer, there should be plenty all over internet. Hope it helps.

EDIT2 Working example of a media player on a Fragment:

Activity layout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame" />

Fragment layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="Playing Music from Resources"
        android:textSize="20dp" />

    <Button
        android:id="@+id/play"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:text="Play" />

    <Button
        android:id="@+id/stop"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:text="Stop" />

</LinearLayout>

Activity code:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction().add(R.id.container, new MyFragment()).commit();
        }
    }
}

Fragment code:

public class MyFragment extends Fragment {

    MediaPlayer mPlayer;
    Button buttonPlay;
    Button buttonStop;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.my_fragment, container, false);

        buttonPlay = (Button)rootView.findViewById(R.id.play);
        buttonPlay.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Uri myUri = Uri.parse("android.resource://com.example.player/" + R.raw.music);
                mPlayer = new MediaPlayer();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    mPlayer.setDataSource(MyFragment.this.getActivity(), myUri);
                } catch (IllegalArgumentException e) {
                    Toast.makeText(MyFragment.this.getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (SecurityException e) {
                    Toast.makeText(MyFragment.this.getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (IllegalStateException e) {
                    Toast.makeText(MyFragment.this.getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    mPlayer.prepare();
                } catch (IllegalStateException e) {
                    Toast.makeText(MyFragment.this.getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    Toast.makeText(MyFragment.this.getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                }
                mPlayer.start();
            }
        });

        buttonStop = (Button)rootView.findViewById(R.id.stop);
        buttonStop.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(mPlayer!=null && mPlayer.isPlaying()){
                    mPlayer.stop();
                }
            }
        });

        return rootView;
    }
}

And that's working and tested, I took the code from here, and the music playes is in raw folder. The others things that you want to add as the seek bar and that just find out how to include it here. But this is the basic. Hope you solve the problem with this.

labreu
  • 444
  • 4
  • 13
  • error went away but when it runs it crashes quickly. =/ – iHateAndroidDev Oct 10 '14 at 00:14
  • i deleted the onCreate and moved it just how you suggested. But it crashed still. gives an error : caused by java.lang.nullpointerexception at com.example.MainFragment.iniializeViews() com.example.MainFragment.onCreateView() – iHateAndroidDev Oct 10 '14 at 00:23
  • Error:(32, 59) error: inconvertible types required: MediaPlayer found: View - i put it in the initializeViews, is that correct place? – iHateAndroidDev Oct 10 '14 at 00:39
  • Thank you for your time and advice, i will keep looking online for fragment examples using media players. I only seem to find only examples using activity's. – iHateAndroidDev Oct 10 '14 at 02:26
  • ok give a minute, I'll update the response with a working example, let you know when ready with a comment, it could help others looking for the same – labreu Oct 10 '14 at 02:31
0

Using your original posted code, remove the line

mediaPlayer = MediaPlayer.create(this, R.raw.no_diggity);

from initializeViews() method and

Do this:

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    mediaPlayer = MediaPlayer.create(getActivity(), R.raw.no_diggity);
    mediaPlayer.start();
    initializeViews();
    return rootView;
}

This question has been answered in another post:

Android: mediaplayer create

Community
  • 1
  • 1
Wildroid
  • 864
  • 7
  • 9
  • i have tried it and it gives me this error: - Error:(50, 9) error: method initializeViews in class MainFragment cannot be applied to given types; required: Context found: no arguments reason: actual and formal argument lists differ in length – iHateAndroidDev Oct 10 '14 at 00:44
  • did you call initializeViews(this); in onCreate() – Wildroid Oct 10 '14 at 01:13
  • just did and i gives me this now: -Error:(35, 9) error: method initializeViews in class MainFragment cannot be applied to given types; required: no arguments found: MainFragment reason: actual and formal argument lists differ in length – iHateAndroidDev Oct 10 '14 at 01:24
  • so i tried your response and it runs but it crashes and it give me a error pointing to the initializeViews and the onCreate methods. – iHateAndroidDev Oct 10 '14 at 02:17
  • i even moved it to the play method and still no luck =/ – iHateAndroidDev Oct 10 '14 at 02:20
  • I just used the code and it works fine with the changes I suggested - did you move initializeViews to onCreateView - you should – Wildroid Oct 10 '14 at 02:39
-1

The problem is with the sound file extension or file type.

For example if you have sound.mp3 it not make the problem or if you have sound.wav or sound.WAV in raw folder it makes the error, so i think some version of android studio didn't support wav file .

Red
  • 26,798
  • 7
  • 36
  • 58