使用媒体播放器时出现奇怪的错误

时间:2014-12-01 07:38:47

标签: java android media-player

我是Java的新手,我的朋友帮我写了这段代码。我收到错误因为我认为我使用了错误的语法。我在代码中添加了注释,我遇到了问题。我甚至不确定我是否应该将此代码放在oncreate内部或外部。任何人都可以请指出一个好的Java学习资源的方向。

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends ActionBarActivity {
public MediaPlayer mediaPlayer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    /*super.onCreate(savedInstanceState);*/
    setContentView(R.layout.activity_main);
    getActionBar().hide();
    mediaPlayer = new MediaPlayer();  //getting an error on this line for invalid syntax.

     //not sure what to put here
        playB() throws IOException {
            playSound(R.raw.b)
        } 

    //not sure what to put here
         playSound(int resId) throws IOException {
             URI uri = URI.parse("android://com.max.bead/" + resId);

             if(mediaPlayer.isPlaying())
             {
                 mediaPlayer.stop();
             }
             else
             {
                 mediaPlayer.setDataSource(getApplicationContext(), uri);
                 mediaPlayer.prepare();
                 mediaPlayer.play();
             }
         }
}

2 个答案:

答案 0 :(得分:1)

试试这个。

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        /*super.onCreate(savedInstanceState);*/
        setContentView(R.layout.activity_main);
        getActionBar().hide();
        mediaPlayer = new MediaPlayer();  //getting an error on this line for invalid syntax.
    }
         //not sure what to put here
            private void playB() throws IOException {
                playSound(R.raw.b);
            } 

        //not sure what to put here
            private void playSound(int resId) throws IOException {
                 URI uri = URI.parse("android://com.max.bead/" + resId);

                 if(mediaPlayer.isPlaying())
                 {
                     mediaPlayer.stop();
                 }
                 else
                 {
                     mediaPlayer.setDataSource(getApplicationContext(), uri);
                     mediaPlayer.prepare();
                     mediaPlayer.play();
                 }
            }

答案 1 :(得分:0)

尝试在媒体播放器上设置OnPreparedListener

mediaPlayer.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); } });