Android播放设备输入声音

时间:2015-07-15 03:00:17

标签: android audio

嗨,我对Android编程比较陌生。我正在做一个项目,要求我开发一个应用程序来连接到一个有8个按钮的设备。

该设备通过蓝牙连接到我的Android手机

Android手机=三星Galaxy S4

Android版本= 5.0.1

API = 21

因此,当用户按下按钮时,该设备将在主UI上发送,读取和显示蓝牙数据为0。

1 =未按下按钮。 0 =按下按钮。

所以它都标记为Pins。

Pin 1 [0] - >按下设备上的按钮

Pin 2 [1]

Pin 3 [1]

Pin 4 [1]

Pin 5 [1]

Pin 6 [1]

Pin 7 [1]

Pin 8 [1]

问题是,我需要在点击按钮时发出声音。

公共类MainActivity扩展了SherlockFragmentActivity {

private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
private MenuItem startRecord, stopRecord;

private CharSequence title;
private CharSequence drawerTitle;   
private String[] navTitles;
private TypedArray navIcons;    
private ArrayList<NavDrawerItem> drawerItems;
private NavDrawerListAdapter adapter;

public static SharedPreferences sp;
private Device device;
private List<Integer> buttonPins;
private SparseArray<Pin> pins;


private Timer timer;
private Timer myTimer;
private TimerTask timerTask;
private TimerTask myTimerTask;
private boolean timerFlag;
private int timeout = 3000;
private ProgressDialog progress;

public static int position = 0;
private boolean active;

public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_DEVICE_NAME = 3;
public static final int MESSAGE_TOAST = 4;
private static final boolean D = true;
private static final String TAG = "MusicFragment";
private String mConnectedDeviceName = null;
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private BTService mBTService = null;

public TextView btMsgTxt;
public Uri uriInstrument;
public ImageView imgInstrument;
public BootstrapButton btnReconnect;
public BootstrapButton btnReselect;

SoundPool instrumentSound;
int recorder1;
int recorder2;
int recorder3;
int recorder4;
int recorder5;
int recorder6;
int recorder7;
int recorder8;
int saxophone1;
int saxophone2;
int saxophone3;
int saxophone4;
int saxophone5;
int saxophone6;
int saxophone7;
int saxophone8;
int bell;

private PinInfo mPinInfo;
private InstrumentSensor mInstrumentSensor;
private HarpPlayer mHarpPlayer;
private RecorderPlayer mRecorderPlayer;
private SaxophonePlayer mSaxophonePlayer;
private BellPlayer mBellPlayer;


private SoundfilePlayer mPlayer;
private boolean mIsplaying;
private InstrumentSoundfiles mInstrumentSoundfiles;
private ArrayList<Integer> currentInstruments;
Timer mTimer;
private boolean mIstimerrunning;
TimerTask retrievePinInfoTask;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sp = PreferenceManager.getDefaultSharedPreferences(this);

    mBluetoothAdapter = BluetoothActivity.mBluetoothAdapter;

    btMsgTxt = (TextView)findViewById(R.id.tv_btMsg);
    imgInstrument = (ImageView)findViewById(R.id.iv_instrument);
    btnReconnect = (BootstrapButton) findViewById(R.id.btn_reconnect);
    btnReselect = (BootstrapButton) findViewById(R.id.btn_reselect);
    loadSound();

    btnReconnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mBTService = null;
            startBTService();
        }

    });
    btnReselect.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            Intent i = new Intent(MainActivity.this,BluetoothActivity.class);
            startActivity(i);
            finish();
        }

    });
    //UI for side drawer
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerList = (ListView) findViewById(R.id.left_drawer);
    navTitles = getResources().getStringArray(R.array.drawer_titles);
    navIcons = getResources().obtainTypedArray(R.array.drawer_icons);

    title = drawerTitle = getTitle();
    // Set a custom shadow that overlays the main content when the drawer opens
    drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    // Set up the drawer's list view with items and click listener
    drawerItems = new ArrayList<NavDrawerItem>();
    drawerItems.add(new NavDrawerItem(navTitles[0], navIcons.getResourceId(0, -1))); // Music       
    drawerItems.add(new NavDrawerItem(navTitles[1], navIcons.getResourceId(1, -1))); // Profile
    drawerItems.add(new NavDrawerItem(navTitles[2], navIcons.getResourceId(2, -1))); // Setting
    drawerItems.add(new NavDrawerItem(navTitles[3], navIcons.getResourceId(3, -1))); // Guide
    navIcons.recycle();

    adapter = new NavDrawerListAdapter(getApplicationContext(), drawerItems);
    drawerList.setAdapter(adapter);
    drawerList.setOnItemClickListener(new DrawerItemClickListener());

    // Enable ActionBar app icon to behave as action to toggle nav drawer
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);


    // ActionBarDrawerToggle ties together the the proper interactions between the sliding drawer and the action bar app icon
    drawerToggle = new ActionBarDrawerToggle(this, /* Host Activity */ drawerLayout, /* DrawerLayout object */
        R.drawable.icon_drawer, /* nav drawer image to replace 'Up' caret */
        R.string.drawer_open, /* "open drawer" description for accessibility */
        R.string.drawer_close /* "close drawer" description for accessibility */
    ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(title);
            invalidateOptionsMenu(); // Creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(drawerTitle);
            invalidateOptionsMenu(); // Creates call to onPrepareOptionsMenu()
        }
    };
    drawerLayout.setDrawerListener(drawerToggle);

    if (savedInstanceState == null) {
        selectItem(0);
    }

    MainActivity.this.setVolumeControlStream(AudioManager.STREAM_MUSIC);

    mInstrumentSoundfiles = ((NinjaTrackApplication)getApplication()).getInstrumentSoundfiles();
    mInstrumentSensor = new InstrumentSensor(mInstrumentSoundfiles);
    mIsplaying = false;
    mPlayer = null;
    currentInstruments = new ArrayList<Integer>();
}


@Override
protected void onResume() {
    startBTService();
    super.onResume();
}

@Override
protected void onStart() {
    super.onStart();
    startBTService();
    active = true;

}

private void startBTService() {
    // If BT is not on, request that it be enabled.
    // setupBTConnSession() will then be called during onActivityResult
    if (mBluetoothAdapter != null)
    {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the Bluetooth connection session
        } else {
            if (mBTService == null) {
                setupBTConnSession();
            }
            connectMe();
        }
    }
    else
    {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }
}

private void setupBTConnSession() {
    Log.d(TAG, "setupBTConnSession()");
    // Initialize the BTService to perform bluetooth connections
    mBTService = new BTService(mHandler);
}

Handler mHandler = new Handler()
{
    @Override
    public void handleMessage(Message msg) {

        switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "mHandler-MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                    case BTService.STATE_CONNECTED:
                        btMsgTxt.setText("Status: Connected to " + mConnectedDeviceName + "!");
                        btnReconnect.setVisibility(View.INVISIBLE);
                        btnReselect.setVisibility(View.INVISIBLE);
                        break;

                    case BTService.STATE_CONNECTING:
                        btMsgTxt.setText("Status: Connecting!");
                        uriInstrument = Uri.parse("android.resource://nyp.fypj.ninjatrack/" + R.drawable.ninjatracklogo);
                        imgInstrument.setImageURI(null);
                        imgInstrument.setImageURI(uriInstrument);
                        break;
                    case BTService.STATE_LISTEN:
                    case BTService.STATE_NONE:
                        uriInstrument = Uri.parse("android.resource://nyp.fypj.ninjatrack/" + R.drawable.ninjatracklogo);
                        imgInstrument.setImageURI(null);
                        imgInstrument.setImageURI(uriInstrument);

                        btMsgTxt.setText("Status: Not Connected!");
                        btnReconnect.setVisibility(View.VISIBLE);
                        btnReselect.setVisibility(View.VISIBLE);
                }
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                Analyzer pinAnalyzer = new Analyzer();
                String instrument = "";
                if(pinAnalyzer.populatePinInfo(readBuf,msg.arg1)){ //populate all Pins
                    try {


                        mPinInfo = pinAnalyzer.populatePin(readBuf, msg.arg1);
                        if(mPinInfo.figure == 4)
                        {
                            //saxophone
                            playSaxophone();
                        }
                        else if(mPinInfo.figure == 5)
                        {
                            //recorder
                            playRecorder();
                        }

                        Log.i(TAG, "mHandler-MESSAGE_READ: " + mPinInfo);
                        btMsgTxt.setText("******\n" + mPinInfo + "\n******");

                    }
                    catch(Exception e)
                    {

                    }
                }
                break;
        }
    }
};

private void connectMe() {
    String deviceName = "FireFly-9A97";
    BluetoothDevice result = null;
    Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
    if (devices != null) {
        for (BluetoothDevice device : devices) {
            if (deviceName.equals(device.getName())) {
                result = device;
                break;
            }
        }
    }
    // Attempt to connect to the device
    if (result != null)
        mBTService.connect(result);
}



private void loadSound()
{
    new Thread(new Runnable() {
        @Override
        public void run() {
            instrumentSound = new SoundPool(10,AudioManager.STREAM_MUSIC,0);
            recorder1 = instrumentSound.load(MainActivity.this,R.raw.recorder1,1);
            recorder2 = instrumentSound.load(MainActivity.this,R.raw.recorder2,1);
            recorder3 = instrumentSound.load(MainActivity.this,R.raw.recorder3,1);
            recorder4 = instrumentSound.load(MainActivity.this,R.raw.recorder4,1);
            recorder5 = instrumentSound.load(MainActivity.this,R.raw.recorder5,1);
            recorder6 = instrumentSound.load(MainActivity.this,R.raw.recorder6,1);
            recorder7 = instrumentSound.load(MainActivity.this,R.raw.recorder7,1);
            recorder8 = instrumentSound.load(MainActivity.this,R.raw.recorder8,1);

            saxophone1 = instrumentSound.load(MainActivity.this,R.raw.saxophone1,1);
            saxophone2 = instrumentSound.load(MainActivity.this,R.raw.saxophone2,1);
            saxophone3 = instrumentSound.load(MainActivity.this,R.raw.saxophone3,1);
            saxophone4 = instrumentSound.load(MainActivity.this,R.raw.saxophone4,1);
            saxophone5 = instrumentSound.load(MainActivity.this,R.raw.saxophone5,1);
            saxophone6 = instrumentSound.load(MainActivity.this,R.raw.saxophone6,1);
            saxophone7 = instrumentSound.load(MainActivity.this,R.raw.saxophone7,1);
            saxophone8 = instrumentSound.load(MainActivity.this,R.raw.saxophone8,1);

            bell = instrumentSound.load(MainActivity.this, R.raw.bell,1);
        }
    }).start();
}

private void playRecorder()
{

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {

                    if (mPinInfo.btn1 == 0) {
                        instrumentSound.play(recorder1, 1, 1, 1, 0, 1);
                    }
                    if (mPinInfo.btn2 == 0) {
                        instrumentSound.play(recorder2, 1, 1, 1, 0, 1);
                    }
                    if (mPinInfo.btn3 == 0) {
                        instrumentSound.play(recorder3, 1, 1, 1, 0, 1);
                    }
                    if (mPinInfo.btn4 == 0) {
                        instrumentSound.play(recorder4, 1, 1, 1, 0, 1);
                    }
                    if (mPinInfo.btn5 == 0) {
                        instrumentSound.play(recorder5, 1, 1, 1, 0, 1);
                    }
                    if (mPinInfo.btn6 == 0) {
                        instrumentSound.play(recorder6, 1, 1, 1, 0, 1);
                    }
                    if (mPinInfo.btn7 == 0) {
                        instrumentSound.play(recorder7, 1, 1, 1, 0, 1);
                    }
                    if (mPinInfo.btn8 == 0) {
                        instrumentSound.play(recorder8, 1, 1, 1, 0, 1);
                    }
            }

            catch (Exception ex) {

            }
        }
    }).start();

}

private void playBell(final PinInfo pi)
{

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                if(pi.accX > 30)
                {

                }
            }

            catch (Exception ex) {

            }
        }
    }).start();

}

private void playSaxophone()
{
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                if (mPinInfo.btn1 == 0) {
                    instrumentSound.play(saxophone1, 1, 1, 1, 0, 1);
                }
                if (mPinInfo.btn2 == 0) {
                    instrumentSound.play(saxophone2, 1, 1, 1, 0, 1);
                }
                if (mPinInfo.btn3 == 0) {
                    instrumentSound.play(saxophone3, 1, 1, 1, 0, 1);
                }
                if (mPinInfo.btn4 == 0) {
                    instrumentSound.play(saxophone4, 1, 1, 1, 0, 1);
                }
                if (mPinInfo.btn5 == 0) {
                    instrumentSound.play(saxophone5, 1, 1, 1, 0, 1);
                }
                if (mPinInfo.btn6 == 0) {
                    instrumentSound.play(saxophone6, 1, 1, 1, 0, 1);
                }
                if (mPinInfo.btn7 == 0) {
                    instrumentSound.play(saxophone7, 1, 1, 1, 0, 1);
                }
                if (mPinInfo.btn8 == 0) {
                    instrumentSound.play(saxophone8, 1, 1, 1, 0, 1);
                }
            }

            catch (Exception ex) {

            }
        }
    }).start();

}



@Override
protected void onStop() {
    super.onStop();
    //instrumentSound.release();
    active = false;
}

当声音响起时,它播放得很好,但有一点失真。目前尚不清楚。

由于我需要产生的声音与乐器类似,声音必须是连续的,就好像有人在播放录音机/萨克斯管一样。

声音也必须混合,例如,如果我同时按下2个按钮,音频必须混合。

我需要提示/建议。谢谢

1 个答案:

答案 0 :(得分:0)

如果你想使用声音并希望它们混合,soundPool是正确的。在youtube上观看这个视频, - https://www.youtube.com/watch?v=L8gEJqGCY28他已经建立了类似的东西。对于失真 - 尝试使用较低的采样率。