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

时间:2014-10-09 23:30:37

标签: android android-fragments android-mediaplayer

我正在尝试制作一个带有播放和停止按钮的简单媒体播放器。但是我收到了一个错误:
方法MediaPlayer.create(Context, int)不适用,方法MediaPlayer.create(Context, Uri, SurfaceHolder)不适用,方法MediaPlayer.create(Context, Uri)不适用。

我看了几篇关于StakeOverflow的帖子,但似乎都没有帮助。谁能开导我?

以下是我发现的一些内容:

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

3 个答案:

答案 0 :(得分:0)

您将片段作为上传传递,而不是传递活动:

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

然后不要使用onCreate方法,把你的initializeViews();在加载视图之后和返回之前调用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 尝试这样的事情,我只是在这里抛出代码,复制/粘贴你的代码,它无法工作,它只是一个关于事情应该如何工作的想法:

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

我的建议是,您首先要查找一些如何使用片段的代码示例,因为您缺少一些基础知识,并且在使用MediaPlayer的工作示例之后,整个互联网应该有很多。希望它有所帮助。

EDIT2 片段上的媒体播放器的工作示例:

活动布局:

<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" />

片段布局:

<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>

活动代码:

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

片段代码:

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

这项工作和测试,我从here获取代码,音乐播放器位于原始文件夹中。您希望添加为搜索栏的其他内容,以及如何在此处添加它。但这是基本的。希望你用这个解决问题。

答案 1 :(得分:0)

使用原始发布的代码,删除

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

来自initializeViews()方法和

这样做:

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

这个问题已在另一篇文章中得到解答:

Android: mediaplayer create

答案 2 :(得分:-1)

问题出在声音文件扩展名或文件类型。

例如,如果您有sound.mp3不会出现问题,或者如果您在原始文件夹中有sound.wavsound.WAV就会出错,所以我认为某些版本的android studio没有不支持wav文件。