简体   繁体   English

Android 错误方法 MediaPlayer.create( ) 不适用

[英]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,方法MediaPlayer.create(Context, int)不适用,
method MediaPlayer.create(Context, Uri, SurfaceHolder) is not applicable,方法MediaPlayer.create(Context, Uri, SurfaceHolder)不适用,
method MediaPlayer.create(Context, Uri) is not applicable.方法MediaPlayer.create(Context, Uri)不适用。

I have looked at a few post on StakeOverflow but none of them seem to have helped.我看过一些关于 StakeOverflow 的帖子,但似乎都没有帮助。 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 无法在 Android 应用程序的 new View.OnFocusChangeListener() 中使用 MediaPlayer.create

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();然后不要使用 onCreate 方法,把你的 initializeViews(); call in the onCreateView() method after load the view and before returning it在加载视图之后和返回之前调用 onCreateView() 方法

@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.我的建议是,您首先要寻找一些有关如何使用片段的代码示例,因为您缺少一些基础知识,在使用 MediaPlayer 的工作示例之后,互联网上应该有很多。 Hope it helps.希望能帮助到你。

EDIT2 Working example of a media player on a Fragment: EDIT2 片段上媒体播放器的工作示例:

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); mediaPlayer = MediaPlayer.create(this, R.raw.no_diggity);

from initializeViews() method and从 initializeViews() 方法和

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 Android:媒体播放器创建

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 .例如,如果您有sound.mp3就不会出现问题,或者如果您在 raw 文件夹中有sound.wavsound.WAV出错,所以我认为某些版本的 android studio 不支持 wav 文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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