Android開發之為按鈕添加音效執行個體

來源:互聯網
上載者:User

1.layout布局檔案:

 代碼如下 複製代碼

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background=”@drawable/activity_background” >

<TextView
android:id=”@+id/title_bar”
android:layout_width=”fill_parent”
android:layout_height=”45dip”
android:layout_alignParentTop=”true”
android:gravity=”center_vertical|center_horizontal”
android:background=”@drawable/theme_title_red”
android:textSize=”25dip”
android:textColor=”#fff”
android:text=”按鍵聲測試”
tools:context=”.MainActivity” />
<Button
android:id=”@+id/btn_test”
android:layout_width=”80dip”
android:layout_height=”30dip”
android:layout_below=”@+id/title_bar”
android:layout_marginLeft=”100dip”
android:layout_marginTop=”20dip”
android:background=”@drawable/bg_btn_submit_selecter”
/>

</RelativeLayout>

 

2.Activity檔案:

 代碼如下 複製代碼

package com.jun.activity;

import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
public Button btn=null;
private SoundPool sp;//聲明一個SoundPool
private int music;//定義一個整型用load();來設定suondID

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

private void init() {
// TODO Auto-generated method stub
btn=(Button) findViewById(R.id.btn_test);
sp= new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);//第一個參數為同時播放資料流的最大個數,第二資料流類型,第三為聲音品質
music = sp.load(this, R.raw.key_sound, 1); //把你的聲音素材放到res/raw裡,第2個參數即為資源檔,第3個為音樂的優先順序

btn.setOnClickListener(listener);
}
private OnClickListener listener =new OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
sp.play(music, 1, 1, 0, 0, 1);

}};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

3.點擊提交按鈕,就會自動播放, /src/raw檔案夾下的key_sound.mp3音樂檔案!!!!!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.