Repository navigation
Expand file tree
/
Copy pathVoiceCallActivity.java
More file actions
472 lines (420 loc) · 19.4 KB
/
Copy pathVoiceCallActivity.java
File metadata and controls
472 lines (420 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
package com.example.wmchat2026;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class VoiceCallActivity extends Activity {
private static final String TAG = "VoiceCallActivity";
private TextView tvStatus, tvTimer;
private ProgressBar pbUpload, pbDownload;
private Button btnHangup;
private Handler mainHandler = new Handler(Looper.getMainLooper());
private volatile boolean isCalling = true;
private volatile boolean callConnected = false;
private long startTime;
private final int SAMPLE_RATE = 8000;
private AudioRecord audioRecord;
private AudioTrack audioTrack;
private int recordBufferSize;
private int playBufferSize;
private String token, friendName;
private int uploadSeq = 0;
private int lastDownloadSeq = 0;
private static final int REQ_MIC = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
// 全局未捕获异常处理(开发调试用)
Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> {
Log.e(TAG, "Uncaught exception in thread " + thread.getName(), ex);
});
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_voice_call);
tvStatus = findViewById(R.id.tvStatus);
tvTimer = findViewById(R.id.tvTimer);
pbUpload = findViewById(R.id.pbUpload);
pbDownload = findViewById(R.id.pbDownload);
btnHangup = findViewById(R.id.btnHangup);
// 防御:确保 view 不为 null
if (tvStatus == null || tvTimer == null || pbUpload == null || pbDownload == null || btnHangup == null) {
Log.e(TAG, "layout views are null — check activity_voice_call.xml ids");
Toast.makeText(this, "布局初始化失败,请检查布局文件", Toast.LENGTH_LONG).show();
finish();
return;
}
token = getIntent().getStringExtra("token");
friendName = getIntent().getStringExtra("friend");
if (token == null || friendName == null) {
Toast.makeText(this, "参数错误(token/friend 为空)", Toast.LENGTH_SHORT).show();
finish();
return;
}
btnHangup.setOnClickListener(v -> hangup());
// 权限检查(运行时)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, REQ_MIC);
// 等待回调 onRequestPermissionsResult,然后再启动轮询
tvStatus.setText("等待麦克风权限...");
return;
}
}
// 有权限时启动
tvStatus.setText("准备中...");
mainHandler.postDelayed(() -> safeRun(this::startStatusPolling), 300);
} catch (Throwable t) {
// 任何 onCreate 中异常都记录并提示,防止白屏崩溃
Log.e(TAG, "onCreate failed", t);
Toast.makeText(this, "启动失败: " + t.getClass().getSimpleName(), Toast.LENGTH_LONG).show();
finish();
}
}
/** 权限回调:用户授予后启动轮询 */
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
try {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQ_MIC) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
tvStatus.setText("权限已授予,启动中...");
mainHandler.postDelayed(() -> safeRun(this::startStatusPolling), 200);
} else {
Toast.makeText(this, "需要麦克风权限才能通话", Toast.LENGTH_LONG).show();
tvStatus.setText("无麦克风权限");
// 不 finish,让用户手动返回;也可 finish() 根据需求
}
}
} catch (Throwable t) {
Log.e(TAG, "onRequestPermissionsResult error", t);
}
}
/** 全局线程异常捕获包装 */
private void safeRun(Runnable r) {
try {
r.run();
} catch (Throwable t) {
Log.e(TAG, "safeRun thread error", t);
}
}
/** 状态轮询(在子线程中运行) */
private void startStatusPolling() {
new Thread(() -> {
while (isCalling && !callConnected) {
try {
String urlStr = "http://wm.51ezu.com/wechat.php?action=voice_call_status&token="
+ URLEncoder.encode(token, "UTF-8")
+ "&to=" + URLEncoder.encode(friendName, "UTF-8");
String resp = httpGet(urlStr);
if (resp != null) {
if (resp.trim().startsWith("{")) {
JSONObject json = new JSONObject(resp);
JSONObject data = json.optJSONObject("data");
String status = (data != null) ? data.optString("status") : "";
if ("accepted".equals(status)) {
callConnected = true;
mainHandler.post(this::startAudioEngine);
break;
} else if ("none".equals(status)) {
mainHandler.post(() -> {
tvStatus.setText("对方已挂断");
hangup();
});
break;
} else {
Log.d(TAG, "call status: " + status);
mainHandler.post(() -> tvStatus.setText("状态: " + status));
}
} else {
Log.w(TAG, "non-json response: " + resp);
}
} else {
Log.w(TAG, "status poll returned null");
}
Thread.sleep(2000);
} catch (Throwable t) {
Log.e(TAG, "status poll error", t);
try { Thread.sleep(2000); } catch (InterruptedException ignored) {}
}
}
}, "vc-status-poll").start();
}
/** 启动音频引擎(在主线程被调用以更新 UI,然后创建子线程做录音/播放) */
private void startAudioEngine() {
try {
tvStatus.setText("准备音频...");
// 计算录音与播放的最小 buffer
recordBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
int minPlay = AudioTrack.getMinBufferSize(SAMPLE_RATE,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT);
if (recordBufferSize <= 0 || minPlay <= 0) {
Log.e(TAG, "Invalid buffer sizes: record=" + recordBufferSize + " playMin=" + minPlay);
Toast.makeText(this, "音频设备不支持该参数", Toast.LENGTH_LONG).show();
return;
}
// 取更大值以保证播放缓冲足够
playBufferSize = Math.max(recordBufferSize, minPlay);
// 保护性 try/catch 创建设备
try {
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, recordBufferSize);
} catch (Throwable t) {
Log.e(TAG, "create AudioRecord failed", t);
Toast.makeText(this, "创建麦克风失败", Toast.LENGTH_SHORT).show();
return;
}
try {
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, playBufferSize,
AudioTrack.MODE_STREAM);
} catch (Throwable t) {
Log.e(TAG, "create AudioTrack failed", t);
Toast.makeText(this, "创建播放设备失败", Toast.LENGTH_SHORT).show();
if (audioRecord != null) {
try { audioRecord.release(); } catch (Throwable ignored) {}
audioRecord = null;
}
return;
}
if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
Log.e(TAG, "AudioRecord not initialized");
Toast.makeText(this, "麦克风初始化失败", Toast.LENGTH_SHORT).show();
try { audioRecord.release(); } catch (Throwable ignored) {}
audioRecord = null;
try { audioTrack.release(); } catch (Throwable ignored) {}
audioTrack = null;
return;
}
if (audioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
Log.e(TAG, "AudioTrack not initialized");
Toast.makeText(this, "播放设备初始化失败", Toast.LENGTH_SHORT).show();
try { audioRecord.release(); } catch (Throwable ignored) {}
audioRecord = null;
try { audioTrack.release(); } catch (Throwable ignored) {}
audioTrack = null;
return;
}
// 启动录音/上传与下载/播放线程(均通过 safeRun 包裹)
new Thread(() -> safeRun(this::recordingAndUploadTask), "vc-upload").start();
new Thread(() -> safeRun(this::downloadAndPlayTask), "vc-download").start();
tvStatus.setText("通话中");
startTime = System.currentTimeMillis();
mainHandler.post(timerRunnable);
} catch (Throwable t) {
Log.e(TAG, "startAudioEngine error", t);
Toast.makeText(this, "启动音频失败", Toast.LENGTH_SHORT).show();
}
}
/** 录音并上传(在子线程) */
private void recordingAndUploadTask() {
try {
if (audioRecord == null) {
Log.e(TAG, "record task: audioRecord is null");
return;
}
audioRecord.startRecording();
byte[] pcmBuffer = new byte[recordBufferSize];
while (isCalling && callConnected) {
int read = audioRecord.read(pcmBuffer, 0, pcmBuffer.length);
if (read <= 0) {
Log.w(TAG, "audio read <=0: " + read);
try { Thread.sleep(50); } catch (InterruptedException ignored) {}
continue;
}
byte[] dataToSend = new byte[read];
System.arraycopy(pcmBuffer, 0, dataToSend, 0, read);
String b64 = Base64.encodeToString(dataToSend, Base64.NO_WRAP);
uploadSeq++;
String postData = "to=" + URLEncoder.encode(friendName, "UTF-8")
+ "&seq=" + uploadSeq + "&data=" + URLEncoder.encode(b64, "UTF-8");
httpPost("http://wm.51ezu.com/wechat.php?action=voice_chunk_send&token=" + token, postData);
final int progress = uploadSeq % 100;
mainHandler.post(() -> {
try { pbUpload.setProgress(progress); } catch (Throwable ignored) {}
});
// 限流,避免 CPU 飙高与频繁 GC
try { Thread.sleep(80); } catch (InterruptedException ignored) {}
}
} catch (Throwable t) {
Log.e(TAG, "recordingAndUploadTask error", t);
} finally {
try {
if (audioRecord != null) {
audioRecord.stop();
audioRecord.release();
audioRecord = null;
}
} catch (Throwable t) {
Log.e(TAG, "release audioRecord failed", t);
}
}
}
/** 下载并播放(在子线程) */
private void downloadAndPlayTask() {
try {
if (audioTrack == null) {
Log.e(TAG, "play task: audioTrack is null");
return;
}
audioTrack.play();
while (isCalling && callConnected) {
String url = "http://wm.51ezu.com/wechat.php?action=voice_chunk_pull&token=" + token
+ "&from=" + URLEncoder.encode(friendName, "UTF-8")
+ "&lastseq=" + lastDownloadSeq;
String resp = httpGet(url);
if (resp != null && resp.trim().startsWith("{")) {
JSONObject json = new JSONObject(resp);
JSONObject dataObj = json.optJSONObject("data");
String b64 = (dataObj != null) ? dataObj.optString("data") : "";
if (b64 != null && !b64.isEmpty()) {
byte[] audioData = Base64.decode(b64, Base64.DEFAULT);
// 安全写入:可能会抛异常,捕获
try {
audioTrack.write(audioData, 0, audioData.length);
lastDownloadSeq++;
final int progress = lastDownloadSeq % 100;
mainHandler.post(() -> {
try { pbDownload.setProgress(progress); } catch (Throwable ignored) {}
});
} catch (Throwable writeEx) {
Log.e(TAG, "audioTrack.write error", writeEx);
}
}
} else if (resp != null) {
Log.w(TAG, "non-json response: " + resp);
}
try { Thread.sleep(120); } catch (InterruptedException ignored) {}
}
} catch (Throwable t) {
Log.e(TAG, "downloadAndPlayTask error", t);
} finally {
try {
if (audioTrack != null) {
audioTrack.stop();
audioTrack.release();
audioTrack = null;
}
} catch (Throwable t) {
Log.e(TAG, "release audioTrack failed", t);
}
}
}
/** 简单的 httpGet(会打印 http code 与响应) */
private String httpGet(String urlStr) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(urlStr).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
int code = conn.getResponseCode();
InputStream is = (code >= 200 && code < 400) ? conn.getInputStream() : conn.getErrorStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while (is != null && (len = is.read(buffer)) != -1) baos.write(buffer, 0, len);
String resp = baos.toString("UTF-8");
Log.d(TAG, "HTTP GET code=" + code + ", resp=" + resp);
return resp;
} catch (Throwable t) {
Log.e(TAG, "httpGet failed: " + urlStr, t);
return null;
} finally {
try { if (conn != null) conn.disconnect(); } catch (Throwable ignored) {}
}
}
/** 简单的 httpPost(打印 code) */
private void httpPost(String urlStr, String postData) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(urlStr).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
OutputStream os = conn.getOutputStream();
os.write(postData.getBytes("UTF-8"));
os.flush();
try { os.close(); } catch (Throwable ignored) {}
int code = conn.getResponseCode();
Log.d(TAG, "HTTP POST code=" + code + ", postData(len)=" + (postData==null?0:postData.length()));
} catch (Throwable t) {
Log.e(TAG, "httpPost failed: " + urlStr, t);
} finally {
try { if (conn != null) conn.disconnect(); } catch (Throwable ignored) {}
}
}
/** 挂断 */
private void hangup() {
isCalling = false;
callConnected = false;
try {
mainHandler.post(() -> {
try { tvStatus.setText("已挂断"); } catch (Throwable ignored) {}
});
} catch (Throwable ignored) {}
new Thread(() -> httpGet("http://wm.51ezu.com/wechat.php?action=voice_call_end&token=" + token), "vc-endcall").start();
mainHandler.postDelayed(this::finish, 800);
}
/** 通话计时器 */
private final Runnable timerRunnable = new Runnable() {
@Override
public void run() {
if (isCalling && callConnected) {
long elapsed = (System.currentTimeMillis() - startTime) / 1000;
mainHandler.post(() -> {
try { tvTimer.setText(String.format("%02d:%02d", elapsed / 60, elapsed % 60)); } catch (Throwable ignored) {}
});
mainHandler.postDelayed(this, 1000);
}
}
};
@Override
protected void onDestroy() {
isCalling = false;
callConnected = false;
// 释放资源(若没释放会在下一次进入时再次尝试)
try {
if (audioRecord != null) {
audioRecord.stop();
audioRecord.release();
audioRecord = null;
}
} catch (Throwable ignored) {}
try {
if (audioTrack != null) {
audioTrack.stop();
audioTrack.release();
audioTrack = null;
}
} catch (Throwable ignored) {}
super.onDestroy();
}
}