小試身手卻發生小問題: 直接放在onCreate裡,卻放不出音效? why?

1. 嘗試了很多次都不能在onCreate裡播放音效,但很多時候需要在一開啟Activity時就發出音效。

2. 原來問題出在於播放音效的時候,音效檔尚未加載完成所以在DDMS上會出現sample not ready的訊息,沒有完成載入音效檔導致不能播放。

3. 解決方法為給程式一點時間去載入音效檔,至於需要多少時間會因音效檔大小而定,礙於SoundPool本身使用上限制音效檔不能超過1mb,所以也不需要花太多時間去載入。本程式的音效檔17kb 我使用了40ms去加載。

4. 使用timer物件runnable方法來給程式時間,timer物件使用方法可參考這篇文章  [Android] 倒數計時器 Runnable

5. 基本SoundPool 請參考這篇 Android] SoundPool 音效 (按鈕版)

小試身手小範例

device035  

java檔

import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;

public class SoundTest extends Activity {

private int alertId;
private SoundPool soundPool;
Handler aHandler;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);

soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 1);
alertId = soundPool.load(this, R.raw.b_072, 1);
aHandler = new Handler();
aHandler.post(runnable);
}
final Runnable runnable = new Runnable() {
public void run() {
try{
Thread.sleep(100);  
}catch(InterruptedException e){
e.printStackTrace();
}
soundPool.play(alertId, 1, 1, 0, 1, 1);
}};
}

XML檔

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Welcome to Android develop world! "
android:textSize="35sp"
android:layout_margin="15sp"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This example is talking about how to use SoundPool."
android:textSize="20sp"
android:layout_margin="15sp"
/>
</LinearLayout>

arrow
arrow

    S 發表在 痞客邦 留言(0) 人氣()