android仿微信语音聊天功能,Android仿微信发送语音消息的功能及示例代码
//...此处省略了一些代码public class VoiceActivity extends AppCompatActivity {
private Button btnRecord;
private Button btnCancel;
private Button btnSend;
private TextView txtHint;
private String audioFilePath;
private MediaRecorder mediaRecorder;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice);
btnRecord = findViewById(R.id.btn_record);
btnCancel = findViewById(R.id.btn_cancel);
btnSend = findViewById(R.id.btn_send);
txtHint = findViewById(R.id.txt_hint);
btnRecord.setOnTouchListener(new View.OnTouchListener() {
@Override public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
startRecording();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
stopRecording();
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
cancelRecording();
}
return true;
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
sendVoiceMessage();
}
});
}
private void startRecording() {
try {
audioFilePath = getExternalCacheDir().getAbsolutePath() + "/audio.3gp";
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioChannels(1);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(audioFilePath);
mediaRecorder.prepare();
mediaRecorder.start();
txtHint.setText("Recording...");
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopRecording() {
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
txtHint.setText("Recorded");
}
}
private void cancelRecording() {
if (mediaRecorder != null) {
mediaRecorder.release();
mediaRecorder = null;
File audioFile = new File(audioFilePath);
if (audioFile.exists()) {
audioFile.delete();
}
txtHint.setText("Cancelled");
}
}
private void sendVoiceMessage() {
// In this example, we assume that the voice message is sent to a chat room ChatRoom chatRoom = new ChatRoom();
chatRoom.sendVoiceMessage(audioFilePath);
}
}
在上面的代码中,我们创建了一个VoiceActivity类来处理语音消息的录制和发送。当用户按住录音按钮时,startRecording()方法会被调用,该方法创建了一个MediaRecorder对象,并设置了一些参数,然后开始录制声音。当用户松开录音按钮时,stopRecording()方法会被调用,该方法会停止录制,并保存所录制的声音文件。如果用户取消录制,则会调用cancelRecording()方法来停止录制并删除录制的声音文件。
当用户点击发送按钮时,sendVoiceMessage()方法会被调用,该方法会将录制的声音文件发送给指定的聊天室。在真实的应用中,发送声音消息的逻辑会更加复杂,并且还需要处理一些额外的功能,比如录制时长限制、录制声音的波形显示、发送进度显示等等。
另外,为了使语音消息更加用户友好,我们还可以使用一些动画效果或者声音波形显示效果来增加用户体验。
总的来说,实现微信语音消息功能并不是很复杂,只需要理解基本的录音和播放功能,并结合Android的UI控件来实现相应的交互即可。希望以上示例代码和描述对你有所帮助。