1. 程式人生 > >電話監聽的小案例實現(Android Studio)

電話監聽的小案例實現(Android Studio)

       最近在做語音識別相關的業務,裡面有語音合成(TTS)本地檔案的實現,我想自己錄一個音訊檔案,不然監聽一下通話的資料,看一看合成的效果怎麼樣了,於是就做了這樣一個小demo,實現監聽並本地儲存通話語音記錄;由於使用的模擬器,所以很多地方有限制,比如不能麥的選擇只能是MIC不能是CALL(一個單向,一個雙向);不過後面都可以優化。

1,通常這個都是做成一個服務,這裡我為了測試方便,就做成了通過點選按鈕(開啟服務)來實現繫結電話監聽服務(RecordService),具體程式碼如下:

(1)activity_main.xml檔案如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="pay.com.huaya.MainActivity">

    <Button
        android:id="@+id/bu_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="開啟監聽"
        android:onClick="click1"
        />

</LinearLayout>

(2)MainActivity程式碼如下:

package pay.com.huaya;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button button;
    private RecordService recordService;
    private MyServiceConnection myServiceConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.bu_1);

    }

    public void click1(View view) {
        String tempContent = button.getText().toString();
        System.out.println(tempContent);
        if (tempContent.equals("開啟監聽")) {
            button.setText("關閉監聽");
            recordService = new RecordService();
            myServiceConnection = new MyServiceConnection();
            Intent intent = new Intent(this, RecordService.class);
            //繫結服務
            bindService(intent, myServiceConnection, BIND_AUTO_CREATE);

        } else {
            button.setText("開啟監聽");
            //解綁服務
            unbindService(myServiceConnection);
        }
    }
    
    private class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

}

(3)RecordService程式碼如下:

package pay.com.huaya;

import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Binder;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

/**
 * @author  why
 * 
 */
public class RecordService extends Service {
    MyPhoneStateListener myPhoneStateListener;
    private MediaRecorder mediaRecorder;

    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("服務繫結成功");
        return null;
    }

    //重寫該方法
    @Override
    public void onCreate() {
        System.out.println("服務建立成功");
        //獲取電話管理者例項
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

        //註冊自定義電話監聽器
        myPhoneStateListener = new MyPhoneStateListener();
        telephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        super.onCreate();
    }


    //自定義電話監聽器
    private class MyPhoneStateListener extends PhoneStateListener {
        //重寫裡面的onCallStateChanged()方法
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {

            switch (state) {
                //空閒狀態
                case TelephonyManager.CALL_STATE_IDLE:
                    if(mediaRecorder!=null){
                     mediaRecorder.stop();
                     mediaRecorder.reset();
                     mediaRecorder.release();
                }
                    break;
                //接聽狀態
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    System.out.println("開始錄音");
                    mediaRecorder.start();
                    break;
                //響鈴狀態
                case TelephonyManager.CALL_STATE_RINGING:
                    System.out.println("有人來電");
                    recodeFun();
                    break;

            }
            super.onCallStateChanged(state, incomingNumber);
        }
    }

    private void recodeFun(){
//初始化錄音機
       mediaRecorder=new MediaRecorder();
       //設定音訊來源,mic單向,call雙向
       mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
       //設定輸出格式
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        //設定編碼方式
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        //設定輸出檔案路徑,使用當前時間作為檔名的一部分
        Calendar calendar=Calendar.getInstance();
        int hour=calendar.get(Calendar.HOUR);
        String subPath=""+hour+"/"+calendar.get(Calendar.SECOND);
        System.out.println("路徑為:/mnt/sdcard/"+subPath);
        mediaRecorder.setOutputFile("/mnt/sdcard/"+subPath+".3gp");
        try {
            //準備與開始錄音
            mediaRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

(4)AndroidManifest檔案程式碼如下(主要是部分許可權和一個服務):

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pay.com.huaya">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <service
            android:name=".RecordService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

    <!--額外的許可權-->
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>

</manifest>

2,測試結果如下

(1)開啟應用,如下圖:

(2)點選“開啟監聽”:

(3)模擬打電話,實現監聽:

(4)點選接聽,說話,結束通話,觀察輸出的檔案路徑與本地儲存的音訊檔案(可以匯出播放):

這個可以結合很多應用開發新的功能與應用,後期我會繼續跟進,希望各位多多指教。