以编程方式连接到配对的蓝牙音箱和播放音频 [英] Programmatically connect to paired Bluetooth speaker and play audio

查看:1993
本文介绍了以编程方式连接到配对的蓝牙音箱和播放音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的应用程序,我想连接到previously配对的A2DP蓝牙音箱和直接音频播放它,采用Android 4.2版或更高版本。

In our app, I'd like to connect to a previously paired A2DP Bluetooth Speaker and direct audio playback to it, using Android v4.2 or later.

我可以用这个code,启动过程中成功地创建一个支持A2DP对象:

I can successfully create an A2DP profile object using this code to start the process:

/* Manifest permissions */
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>


// Get the default adapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.A2DP)

和下面的听众向连接响应:

And the following listener to respond to the connection:

private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {

    if (profile == BluetoothProfile.A2DP) {

        mBluetoothSpeaker = (BluetoothA2dp) proxy;

        // no devices are connected         
        List<BluetoothDevice> connectedDevices = mBluetoothSpeaker.getConnectedDevices();

        //the one paired (and disconnected) speaker is returned here
        int[] statesToCheck = {BluetoothA2dp.STATE_DISCONNECTED};           
        List<BluetoothDevice> disconnectedDevices = mBluetoothSpeaker.getDevicesMatchingConnectionStates(statesToCheck);



        BluetoothDevice btSpeaker = disconnectedDevices.get(0); 

        //WHAT NOW?

    }
}
public void onServiceDisconnected(int profile) {
    if (profile == BluetoothProfile.A2DP) {
        mBluetoothSpeaker = null;
    }
}
};

我只是一点点丢失到现在做什么,连接设备,并指示音频输出给它。我试着连接到设备,详见Android的文档,具有以下code,但最后 BluetoothSpeaker.getConnectedDevices()调用返回无连接的设备。

I'm just a little lost as to what to do now, to connect the device, and direct the audio output to it. I've tried connecting to the device, as detailed in the Android docs, with the following code, but the final BluetoothSpeaker.getConnectedDevices() call returns no connected devices.

    BluetoothSocket tmp = null;
    UUID MY_UUID = UUID.fromString("00001108-0000-1000-8000-00805f9b34fb");
    try {           
        tmp = btSpeaker.createInsecureRfcommSocketToServiceRecord(MY_UUID);

    } catch (IOException e1) {
        // TODO Auto-generated catch block
        Log.d("createRfcommSocketToServiceRecord ERROR", e1.getMessage());
    }
    mmSocket = tmp;

    try {
        // Connect the device through the socket. This will block
        // until it succeeds or throws an exception
        mmSocket.connect();
    } catch (IOException connectException) {
        // Unable to connect; close the socket and get out
        try {
            Log.d("connectException", connectException.getMessage());
            mmSocket.close();
        } catch (IOException closeException) { }
        return;
    }

    connectedDevices = mBluetoothSpeaker.getConnectedDevices();

在code似乎并连接到该设备在某些方面虽然,因为当我停止执行,蓝牙音箱annouces,它准备对(因为它总是当它从一个音频源断开一样)。

The code does seem to connect to the device in some way though, as when I stop execution, the Bluetooth speaker annouces that it is ready to pair (as it always does when it disconnects from an audio source).

旧版本的 BluetoothA2dp 似乎有一个连接(BluetoothDevice类设备)的方法,但现在已经删除(如4.2),我在努力寻找如何以编程方式连接到A2DP设备的任何明显的例子,并指示音频输出它。就如何解决或者任何帮助将受到欢迎。

Older versions of the BluetoothA2dp seem to have a connect(BluetoothDevice device) method, but that has now been removed (as of 4.2) and I'm struggling to find any clear examples of how to programmatically connect to an A2DP device, and to direct audio output to it. Any help on how to approach either would be gratefully received.

对如何处理这将是巨大的AP preciated任何意见。

Any advice on how to approach this would be hugely appreciated.

推荐答案

这一次为我工作。 收到BluetoothA2dp.STATE_CONNECTED后,您可以播放音乐是正常的。

This one works for me. After receive BluetoothA2dp.STATE_CONNECTED, you can play music as normal.

public class A2DPActivity extends Activity {

protected static final String TAG = "ZS-A2dp";

Button mBtPlay;

BluetoothAdapter mBtAdapter;
BluetoothA2dp mA2dpService;

AudioManager mAudioManager;
MediaPlayer mPlayer;

BroadcastReceiver mReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context ctx, Intent intent) {
        String action = intent.getAction();
        Log.d(TAG, "receive intent for action : " + action);
        if (action.equals(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)) {
            int state = intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, BluetoothA2dp.STATE_DISCONNECTED);
            if (state == BluetoothA2dp.STATE_CONNECTED) {
                setIsA2dpReady(true);
                playMusic();
            } else if (state == BluetoothA2dp.STATE_DISCONNECTED) {
                setIsA2dpReady(false);
            }
        } else if (action.equals(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED)) {
            int state = intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, BluetoothA2dp.STATE_NOT_PLAYING);
            if (state == BluetoothA2dp.STATE_PLAYING) {
                Log.d(TAG, "A2DP start playing");
                Toast.makeText(A2DPActivity.this, "A2dp is playing", Toast.LENGTH_SHORT).show();
            } else {
                Log.d(TAG, "A2DP stop playing");
                Toast.makeText(A2DPActivity.this, "A2dp is stopped", Toast.LENGTH_SHORT).show();
            }
        }
    }

};

boolean mIsA2dpReady = false;
void setIsA2dpReady(boolean ready) {
    mIsA2dpReady = ready;
    Toast.makeText(this, "A2DP ready ? " + (ready ? "true" : "false"), Toast.LENGTH_SHORT).show();
}

private ServiceListener mA2dpListener = new ServiceListener() {

    @Override
    public void onServiceConnected(int profile, BluetoothProfile a2dp) {
        Log.d(TAG, "a2dp service connected. profile = " + profile);
        if (profile == BluetoothProfile.A2DP) {
            mA2dpService = (BluetoothA2dp) a2dp;
            if (mAudioManager.isBluetoothA2dpOn()) {
                setIsA2dpReady(true);
                playMusic();
            } else {
                Log.d(TAG, "bluetooth a2dp is not on while service connected");
            }
        }
    }

    @Override
    public void onServiceDisconnected(int profile) {
        setIsA2dpReady(false);
    }

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LinearLayout ll = new LinearLayout(this);
    setContentView(ll);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    registerReceiver(mReceiver, new IntentFilter(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED));
    registerReceiver(mReceiver, new IntentFilter(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED));

    mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    mBtAdapter.getProfileProxy(this, mA2dpListener , BluetoothProfile.A2DP);

}

@Override
protected void onDestroy() {
    mBtAdapter.closeProfileProxy(BluetoothProfile.A2DP, mA2dpService);
    releaseMediaPlayer();
    unregisterReceiver(mReceiver);
    super.onDestroy();
}

@Override
protected void onPause() {
    releaseMediaPlayer();
    super.onPause();
}

private void releaseMediaPlayer() {
    if (mPlayer != null) {
        mPlayer.release();
        mPlayer = null;
    }
}

private void playMusic() {
    mPlayer = new MediaPlayer();
    AssetManager assetManager = this.getAssets();
    AssetFileDescriptor fd;
    try {
        fd = assetManager.openFd("Radioactive.mp3");
        Log.d(TAG, "fd = " + fd);
        mPlayer.setDataSource(fd.getFileDescriptor());
        mPlayer.prepare();
        Log.d(TAG, "start play music");
        mPlayer.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

这篇关于以编程方式连接到配对的蓝牙音箱和播放音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆