2017-01-11 52 views
0

我有一個問題,即使歌曲位於原始目錄中,按下播放按鈕時仍無法播放媒體播放器。Android工作室媒體播放器無法工作

這裏的代碼如下。

public class MainActivity extends AppCompatActivity { 

    private MediaPlayer mediaPlayer; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

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

     Button play = (Button) findViewById(R.id.play); 

     Button pause = (Button) findViewById(R.id.pause); 


     play.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       //Toast.makeText(MainActivity.this,"Play",Toast.LENGTH_SHORT).show(); 
       mediaPlayer.start(); 
      } 
     }); 


     pause.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       //Toast.makeText(MainActivity.this,"Pause",Toast.LENGTH_SHORT).show(); 
       mediaPlayer.pause(); 
      } 
     }); 

    } 


} 

這裏是下面的佈局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/activity_main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:orientation="vertical" 
    tools:context="com.example.android.musicplayer.MainActivity"> 


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

    <Button 
     android:id="@+id/pause" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Pause"/> 


</LinearLayout> 
+0

提供R.raw.song的內容。 –

+0

如果播放不起作用,您的logcat應該在您的按鈕上打印一些有價值的信息。 –

+1

歌有哪種格式? – Kishan

回答

2
try{ 
    mediaPlayer.prepare(); 
    }catch(Exception e){e.printStackTrace();} 
0

我發現SoundPoolPlayer這比媒體播放器
於Android的Soundpool SoundPoolPlayer定製extention與setOnCompletionListener沒有更好的低MediaPlayer的效率缺點。

創作:

SoundPoolPlayer mPlayer = SoundPoolPlayer.create(context, resId); 
mPlayer.setOnCompletionListener(
    new MediaPlayer.OnCompletionListener() { 
     @Override 
     public void onCompletion(MediaPlayer mp) { //mp will be null here 
      Log.d("debug", "completed"); 
     } 
    }; 
); 

玩法:

mPlayer.play() 

暫停:

mPlayer.pause(); 

站:

mPlayer.stop(); 

簡歷:

mPlayer.resume(); 

IsPlaying模塊:

mPlayer.isPlaying(); 

Here is the Link to Download the player Class

下─快樂編碼

相關問題