我正在尝试通过蓝牙发送和接收语音邮件。 但是没有做到这一点,我搜索了很多,但没有找到一个gud教程。
任何人都可以帮助我吗?
请让我知道我在哪里做错了 非常感谢
以下是我的Updated Class
BluetoothChat :
public class BluetoothChat extends Activity {
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
boolean isRoute = true;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
ToggleButton mspeakButton, mplayButton;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Member object for the chat services
private BluetoothChatService mChatService = null;
static AudioManager mAudioManager;
MediaRecorder myAudioRecorder;
private MediaRecorder myRecorder;
private MediaPlayer myPlayer;
File file;
private String outputFile = null;
boolean toggle = true;
String items = "";
String address = "";
String sdcard_path = "";
private TextView text1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (D)
Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
setContentView(R.layout.main);
//outputFile = getIntent().getExtras().getString("output");
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// store it to sd card
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myRecording.mp3";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
else {
if (mBluetoothAdapter.isEnabled()) {
registerReceiver(ActionFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
mBluetoothAdapter.startDiscovery();
}
}
}
@Override
public void onStart() {
super.onStart();
if (D)
Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
}
else {
if (mChatService == null)
setupChat();
}
}
@Override
public synchronized void onResume() {
super.onResume();
if (D)
Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
mConversationView = (ListView) findViewById(R.id.in);
mConversationView.setAdapter(mConversationArrayAdapter);
// Initialize the compose field with a listener for the return key
mOutEditText = (EditText) findViewById(R.id.edit_text_out);
mOutEditText.setOnEditorActionListener(mWriteListener);
// Initialize the send button with a listener that for click events
mSendButton = (Button) findViewById(R.id.button_send);
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = view.getText().toString();
sendMessage(message);
//SetRouteSco(BluetoothChat.this, isRoute);
}
});
text1 = (TextView) findViewById(R.id.text1);
// Initialize the speak button with a listener that for click events
mspeakButton = (ToggleButton) findViewById(R.id.button_speak);
mspeakButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (toggle) {
toggle = false;
sendvoice(v);
}
else {
toggle = true;
record(v);
}
}
});
// Initialize the play button with a listener that for click events
mplayButton = (ToggleButton) findViewById(R.id.button_play);
mplayButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (toggle) {
toggle = false;
stopPlay(v);
}
else {
toggle = true;
play(v);
}
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
public void sendvoice(View view) {
try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
text1.setText("Recording Point: Stop recording");
Toast.makeText(getApplicationContext(), "Stop recording...", Toast.LENGTH_SHORT).show();
if (mBluetoothAdapter.isEnabled()) {
Log.d("btAdapter", "btAdapter" + mBluetoothAdapter);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("/myRecording.mp3");
sharingIntent.setComponent(new ComponentName("com.android.bluetooth", "com.android.bluetooth.opp.BluetoothOppLauncherActivity"));
file = new File(outputFile);
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
startActivity(sharingIntent);
Log.d("/myRecording.mp3", "SharingIntent");
}
else {
text1.setText("Bluetooth not activated");
}
}
catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
}
catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
public void record(View view) {
try {
myRecorder.prepare();
myRecorder.start();
}
catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
}
catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
text1.setText("Recording Point: Recording");
Toast.makeText(getApplicationContext(), "Start recording...", Toast.LENGTH_SHORT).show();
}
public void stopPlay(View view) {
try {
if (myPlayer != null) {
myPlayer.stop();
myPlayer.release();
myPlayer = null;
text1.setText("Recording Point: Stop playing");
Toast.makeText(getApplicationContext(), "Stop playing the recording...", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void play(View view) {
try {
myPlayer = new MediaPlayer();
myPlayer.setDataSource(outputFile);
myPlayer.prepare();
myPlayer.start();
text1.setText("Recording Point: Playing");
Toast.makeText(getApplicationContext(), "Start play the recording...", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
public synchronized void onPause() {
super.onPause();
if (D)
Log.e(TAG, "- ON PAUSE -");
}
@Override
public void onStop() {
super.onStop();
if (D)
Log.e(TAG, "-- ON STOP --");
}
@Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mChatService != null)
mChatService.stop();
if (D)
Log.e(TAG, "--- ON DESTROY ---");
}
private void ensureDiscoverable() {
if (D)
Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("BroadcastReceiver", "onReceive");
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
items += device.getName() + ",";
address += device.getAddress() + ",";
}
}
};
/**
* Sends a message.
*
* @param message
* A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
// The action listener for the EditText widget, to listen for the return key
private TextView.OnEditorActionListener mWriteListener = new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
//SetRouteSco(BluetoothChat.this, isRoute);
}
if (D)
Log.i(TAG, "END onEditorAction");
return true;
}
};
private final void setStatus(int resId) {
final ActionBar actionBar = getActionBar();
actionBar.setSubtitle(resId);
}
private final void setStatus(CharSequence subTitle) {
final ActionBar actionBar = getActionBar();
actionBar.setSubtitle(subTitle);
}
// The Handler that gets information back from the BluetoothChatService
@SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if (D)
Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
try {
setStatus(R.string.title_not_connected);
}
catch (Exception e) {
e.printStackTrace();
}
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);
/*String readMessage = new String(readBuf, 0, msg.arg1);
try {
re(readMessage);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (SecurityException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);*/
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to " + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
break;
}
}
};
/* public void play(String outputFile) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
MediaPlayer m = new MediaPlayer();
m.setDataSource(outputFile);
m.prepare();
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (D)
Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
}
else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent serverIntent = null;
switch (item.getItemId()) {
case R.id.secure_connect_scan:
// Launch the DeviceListActivity to see devices and do scan
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
case R.id.insecure_connect_scan:
// Launch the DeviceListActivity to see devices and do scan
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
case R.id.discoverable:
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
return false;
}
/* *//**
* Sends a voice message.
*/
/*
public static void SetRouteSco(Context context, boolean isRoute) {
Log.d("SetRouteSco", "isRoute : " + isRoute);
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
mAudioManager.setBluetoothScoOn(isRoute);
if (isRoute)
mAudioManager.startBluetoothSco();
else
mAudioManager.stopBluetoothSco();
}*/
}
XML :
<ListView
android:id="@+id/in"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll" />
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Recording Point: -"
android:textAppearance="?android:attr/textAppearanceMedium" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ToggleButton
android:id="@+id/button_speak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:textOff="send"
android:textOn="speak" />
<EditText
android:id="@+id/edit_text_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_weight="1" />
<Button
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Msg" />
<ToggleButton
android:id="@+id/button_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:textOff="stop"
android:textOn="play" />
</LinearLayout>
舱单类:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.BluetoothChat"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="11" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:icon="@drawable/app_icon"
android:label="@string/app_name" >
<activity
android:name=".MAinActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".BluetoothChat"
android:configChanges="orientation|keyboardHidden"
android:label="@string/select_device"
android:theme="@android:style/Theme.Holo.Dialog" />
<activity
android:name=".DeviceListActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name" />
</application>
</manifest>
注意:首先我将设备与另一台设备配对并成功录制语音,但在将该语音发送到其他设备时,“您未连接到设备”显示的是吐司
重要提示:通过此演示我的音频文件已发送,但它只能直接保存到SD卡, 我希望首先将该音频文件发送到该特定应用程序并保存到SD卡
任何人都可以帮助我? 我怎么能这样做?
谢谢高级
答案 0 :(得分:0)
您需要在两台设备之间建立配对以传输语音留言
1)使用您的应用程序录制语音留言
2)通过蓝牙使用分享发送。