Android 使用ToneGenerator编写按键发声功能

转载: http://www.2cto.com/kf/201312/262961.html

今天给大家介绍的是怎么样使用ToneGenerator编写按键发声功能,这个在我们开发的时候用到的地方很多(例如电话键盘按键),那么我们就来看看吧,下面我们就用一个例子来说说怎么样能实现这个功能。

 

file: MainActivity.java

package com.example.helloworld; import android.media.AudioManager; import android.media.ToneGenerator; import android.os.Bundle; import android.provider.Settings; import android.app.Activity; import android.content.Context; import android.view.Menu; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private Button btn1, btn2, btn3; private int value; private ToneGenerator mToneGenerator; private Object mToneGeneratorLock = new Object(); // 监视器对象锁
    private boolean mDTMFToneEnabled; // 按键操作音
    private static final int TONE_LENGTH_MS = 150; // 延迟时间
    private AudioManager mAudioManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn1 = (Button) findViewById(R.id.button1); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub
                btn1.setText(value + ""); playTone(value); value++; if (value > 9) { value = 0; } } }); btn2 = (Button) findViewById(R.id.button2); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { playTone(42); // *: 42
 } }); btn3 = (Button) findViewById(R.id.button3); btn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { playTone(35); // #: 35
 } }); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mDTMFToneEnabled = Settings.System.getInt(getContentResolver(), Settings.System.DTMF_TONE_WHEN_DIALING, 1) == 1; synchronized (mToneGeneratorLock) { if (mToneGenerator == null) { try { mToneGenerator = new ToneGenerator( AudioManager.STREAM_MUSIC, 80); setVolumeControlStream(AudioManager.STREAM_MUSIC); } catch (Exception e) { e.printStackTrace(); mToneGenerator = null; } } } } // 播放按键声音
    void playTone(int tone) { if (!mDTMFToneEnabled) { return; } int ringerMode = mAudioManager.getRingerMode(); if ((ringerMode == AudioManager.RINGER_MODE_SILENT) || (ringerMode == AudioManager.RINGER_MODE_VIBRATE)) { // 静音或者震动时不发出按键声音
            return; } synchronized (mToneGeneratorLock) { if (mToneGenerator == null) { return; } mToneGenerator.startTone(tone, TONE_LENGTH_MS); // 发声
 } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.main, menu); return true; } }

 

activity_main.xml:

<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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" >

    <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" />

    <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/textView1" android:layout_marginTop="31dp" android:text="Button" />

    <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button1" android:layout_alignBottom="@+id/button1" android:layout_centerHorizontal="true" android:text="Button" />

    <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button2" android:layout_alignBottom="@+id/button2" android:layout_alignParentRight="true" android:text="Button" />

</RelativeLayout>

 

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.helloworld" android:versionCode="1" android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" />

    <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
        <activity android:name="com.example.helloworld.MainActivity" android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 


下面是另一种写法

 

MainActivity.java

 1 package com.example.toneplayer;  2 
 3 import android.media.AudioManager;  4 import android.media.ToneGenerator;  5 import android.os.Bundle;  6 import android.provider.Settings;  7 import android.app.Activity;  8 import android.content.Context;  9 import android.util.Log;  10 import android.view.Menu;  11 import android.view.View;  12 import android.widget.Button;  13 
 14 public class MainActivity extends Activity {  15 
 16     /** Tone音的长度,单位:milliseconds */
 17     private static final int TONE_LENGTH_MS = -1;  18     /** 主音量的比例:以80%的主音量播放Tone音 */
 19     private static final int TONE_RELATIVE_VOLUME = 80;  20     /** 主音量的音频种别 */
 21     private static final int DIAL_TONE_STREAM_TYPE = AudioManager.STREAM_MUSIC;  22     private static final String TAG = "TonePlayer";  23 
 24     // Tone音播放器
 25     private ToneGenerator mToneGenerator;  26     // Tone相关的同步锁
 27     private Object mToneGeneratorLock = new Object();  28     // 设定中的Tone音播放设置
 29     private boolean mDTMFToneEnabled;  30 
 31     private Button btn1, btn2;  32 
 33     private int value;  34 
 35  @Override  36     protected void onCreate(Bundle savedInstanceState) {  37         super.onCreate(savedInstanceState);  38  setContentView(R.layout.activity_main);  39 
 40         btn1 = (Button) findViewById(R.id.button1);  41         btn1.setOnClickListener(new View.OnClickListener() {  42 
 43  @Override  44             public void onClick(View v) {  45                 // TODO Auto-generated method stub
 46                 btn1.setText(value + "");  47  playTone(value);  48                 value++;  49                 if (value > 9) {  50                     value = 0;  51  }  52  }  53  });  54 
 55         btn2 = (Button) findViewById(R.id.button2);  56         btn2.setOnClickListener(new View.OnClickListener() {  57  @Override  58             public void onClick(View v) {  59                 playTone(42); // *: 42
 60  }  61  });  62  }  63 
 64  @Override  65     public boolean onCreateOptionsMenu(Menu menu) {  66         // Inflate the menu; this adds items to the action bar if it is present.
 67  getMenuInflater().inflate(R.menu.main, menu);  68         return true;  69  }  70 
 71     public void onResume() {  72         super.onResume();  73         // 读取设定的值
 74         mDTMFToneEnabled = Settings.System.getInt(getContentResolver(),  75                 Settings.System.DTMF_TONE_WHEN_DIALING, 1) == 1;  76 
 77         // 失败了也无所谓,不是啥重要的东西
 78         synchronized (mToneGeneratorLock) {  79             if (mToneGenerator == null) {  80                 try {  81                     // we want the user to be ableto control the volume of the  82                     // dial tones  83                     // outside of a call, so we usethe stream type that is also  84                     // mapped to the  85                     // volume control keys for thisactivity
 86                     mToneGenerator = new ToneGenerator(DIAL_TONE_STREAM_TYPE,  87  TONE_RELATIVE_VOLUME);  88  setVolumeControlStream(DIAL_TONE_STREAM_TYPE);  89                 } catch (RuntimeException e) {  90  Log.w(TAG,  91                             "Exceptioncaught while creating local tone generator: "
 92                                     + e);  93                     mToneGenerator = null;  94  }  95  }  96  }  97  }  98 
 99     public void onPause() { 100         super.onPause(); 101 
102         synchronized (mToneGeneratorLock) { 103             if (mToneGenerator != null) { 104  mToneGenerator.release(); 105                 mToneGenerator = null; 106  } 107  } 108  } 109 
110     /**
111  * 播放TONE_LENGTH_MS milliseconds的Tone音. 只有在设定中选择了播放Tone,并且不是静音模式才会播放Tone音。 112  * 113  * @param tone 114  * a tone code from {@linkToneGenerator} 115      */
116     void playTone(int tone) { 117         // 设定中没有选中的话,就不播
118         if (!mDTMFToneEnabled) { 119             return; 120  } 121 
122         // 静音模式的时候也不播,需要每次都检查,因为没有Activity切换也能设成静音模式 123         // 设定中的那个就不需要,因为要设定必须要先切入设定Activity才行
124         AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 125         int ringerMode = audioManager.getRingerMode(); 126         if ((ringerMode == AudioManager.RINGER_MODE_SILENT) 127                 || (ringerMode == AudioManager.RINGER_MODE_VIBRATE)) { 128             return; 129  } 130 
131         synchronized (mToneGeneratorLock) { 132             if (mToneGenerator == null) { 133                 Log.w(TAG, "playTone:mToneGenerator == null, tone: " + tone); 134                 return; 135  } 136 
137             // Start the new tone (will stop anyplaying tone)
138  mToneGenerator.startTone(tone, TONE_LENGTH_MS); 139  } 140  } 141 }

 

activity_main.xml:

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="31dp"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="54dp"
        android:text="Button" />

</RelativeLayout>

 

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.toneplayer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.toneplayer.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

你可能感兴趣的:(generator)