[英]Playing a sound on android
在我的第一個應用旅程中,我遇到了另一個錯誤:)我想在應用加載時播放聲音。 這是一個.wav文件。 它持續2秒之久,但是當我在舊的Samsung S4上運行該應用程序時卻無法播放。 IDE內沒有錯誤,也沒有看到任何錯誤,我已經檢查了'mp'是否具有值並且確實存在。 環顧大多數人的帖子都存在'mp'= null的問題。 盡管我的價值很大,但電話不會發出聲音……再次感謝您的幫助!
public class OpeningScreen extends Activity {
@Override
// create the screen state
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// connect the xml layout file
setContentView(R.layout.activity_opening_screen);
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.welcome_message);
mp.start();
// create the on touch listener
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.opening_layout);
layout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// change the screen to a new state
Intent intent = new Intent(OpeningScreen.this, GameScreen.class);
// start the new activity
startActivity(intent);
// stop welcome sound (if still playing)
mp.stop();
return true;
}
});
}
}
public static MediaPlayer create(Context context, int resid)
是為給定資源ID創建MediaPlayer的靜態方法。 這意味着通過調用create可以創建沒有參考用法的媒體播放器新實例。
嘗試改變
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.welcome_message);
至
final MediaPlayer mp = MediaPlayer.create(this, R.raw. welcome_message);
玩家應該工作。
最好通過MediaPlayer.setOnPreaparedListener
注冊OnPreapredListener
,並在准備好之后開始媒體播放。
http://developer.android.com/guide/topics/media/mediaplayer.html
為什么使用final? 您可以播放mp3
MediaPlayer mp = MediaPlayer.create(OpeningScreen.this, R.raw.welcome_message);
mp.start();
如果停止onDestroy,則停止mediaplayer也更好。
public void onDestroy() {
mp.stop();
super.onDestroy();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.