简体   繁体   中英

Android Error method MediaPlayer.create( )is not applicable

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);
    }
};
}

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.

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

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 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM