如何将麦克风音频流式传输到同一设备投掷扬声器

我正在尝试从麦克风获取音频并通过连接到辅助设备的扬声器进行流式传输我使用了此代码,但它在录音机的初始化中不起作用,但我真正的问题是“这是正确的方法还是有更好的方法来做到这一点“如果是如何解决初始化音频的问题

public class MainActivity extends AppCompatActivity {



    private static final String TAG = "MainActivity";

    // the buttons for start and Stop BoadCast

    Button mStartBoadCast;

    Button mStopBoadCast;


    // variables for audio recording

    AudioRecord recorder;

    private int sampleRate = 44100;

    private int channelConfig = AudioFormat.CHANNEL_IN_DEFAULT;

    private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;

    int minBufSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);

    private boolean status = true;


    // audio instance is meant for playing audio input from stream

    private AudioTrack speaker;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        //init layout views

        initViews();


        // init start boadcast method with the button

        initStartBoadCast();


        // init stop boadcast method with the button

        initStartBoadCast();


    }


    private void initStartBoadCast() {

        mStartBoadCast.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                startBoadCast();

            }

        });

    }


    private void initStopBoadCast() {

        mStartBoadCast.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                stopBoadCast();

            }

        });

    }


    private void stopBoadCast() {

        //todo: add the function to stop boad casr

        status = false;

        recorder.release();

        speaker.release();


    }

小怪兽爱吃肉
浏览 124回答 1
1回答

FFIVE

交易是在细节中,你没有告诉我们这是如何不起作用或者它会给出什么样的错误。我必须做一个类似的程序,这就是我所做的。首先是音频类:class audio {AudioRecord arec;AudioTrack atrack;private volatile boolean isRecording= false;private static int buffer_size;//final short[] buffer = new short[buffersize];//short[] readbuffer = new short[buffersize];private int sample_rate;//the rate of recording used to initialise AudioRecordprivate int[] msample_rates = new int[]{44100, 22050, 11025, 8000};private short audio_format;private short[] audio_formats = new short[]{AudioFormat.ENCODING_PCM_8BIT, AudioFormat.ENCODING_PCM_16BIT};private short channel_config;private short[] channel_configs = new short[]{AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO};private short channelOutConfig;public AudioRecord findAudioRecord(){&nbsp; &nbsp; for (int rate_f : msample_rates){&nbsp; &nbsp; &nbsp; &nbsp; for (short audioformat_f : audio_formats){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (short channelconfig_f : channel_configs){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.i("AudioC", "Attempting rate : "+ rate_f + "Hz, bits: " + audioformat_f + ", Channel: " + channelconfig_f);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int buffersize_f = AudioRecord.getMinBufferSize(rate_f, channelconfig_f, audioformat_f);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.i("AudioC", "Buffersize: " + buffersize_f);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (buffersize_f != AudioRecord.ERROR_BAD_VALUE){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Check of we can instantiate and have a success&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, rate_f, channelconfig_f, audioformat_f, buffersize_f);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.i("AudioC", "Recorder State Value: " + recorder.getState());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(recorder.getState() == AudioRecord.STATE_INITIALIZED){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.i("Audio", "Success");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //global values&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; buffer_size = buffersize_f;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sample_rate = rate_f;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; audio_format = audioformat_f;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; channel_config = channelconfig_f;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (channelconfig_f == AudioFormat.CHANNEL_IN_MONO) channelOutConfig = AudioFormat.CHANNEL_OUT_MONO;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else channelOutConfig = AudioFormat.CHANNEL_OUT_STEREO;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return recorder;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }catch (Exception e){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.i("AudioC", rate_f + " Exception, keep trying." + e);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; Log.i("AudioC", "Failed to initialise the audio record state");&nbsp; &nbsp; return null;}public void run(){&nbsp; &nbsp; isRecording = true;&nbsp; &nbsp; //initialization&nbsp; &nbsp; android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO);&nbsp; &nbsp; //getValidSampleRates();&nbsp; &nbsp;// int buffersize = AudioRecord.getMinBufferSize(sample_rate,AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT);&nbsp; &nbsp;// arec = new AudioRecord(MediaRecorder.AudioSource.MIC,sample_rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize);&nbsp; &nbsp; //The above lines were replaced by a looping function in order to test every occurrence of rate,audioformat and channelconfig which is usually different for different adroid devices&nbsp; &nbsp; arec = findAudioRecord();//Still failed to initialize the Audio Recorder&nbsp; &nbsp; atrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sample_rate,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; channelOutConfig,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; audio_format,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; buffer_size,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; AudioTrack.MODE_STREAM);&nbsp; &nbsp; atrack.setPlaybackRate(sample_rate);&nbsp; &nbsp; //run&nbsp; &nbsp; byte[] buffer = new byte[buffer_size];&nbsp; &nbsp; arec.startRecording();&nbsp; &nbsp; atrack.play();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while (isRecording){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arec.read(buffer, 0, buffer_size);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; atrack.write(buffer, 0,buffer.length);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arec.release();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; atrack.release();}public void stop(){&nbsp; &nbsp; isRecording= false;&nbsp; &nbsp; arec.stop();&nbsp; &nbsp; atrack.stop();&nbsp; &nbsp; arec.release();&nbsp; &nbsp; atrack.release();}}然后从活动(主活动)的线程或意图服务中调用它,以避免应用程序冻结。线程示例:class playerTask implements Runnable{public audio mic_player = new audio(); //The audio class we declared aboveprivate Thread t;public playerTask(){}public void execTask(){&nbsp; &nbsp; t = new Thread(this,"playing_Thread");&nbsp; &nbsp; t.start();}public void abortTask(){&nbsp; &nbsp; mic_player.stop();}public void run(){&nbsp; &nbsp; mic_player.run();}}然后从你的活动来看,public class YourActivity extends AppCompatActivity {&nbsp; &nbsp; ToggleButton onOff;&nbsp; &nbsp; boolean playing = false;&nbsp; &nbsp; // Once the app start recording, the recording thread freezes the screen because of the while loop, the it works&nbsp; &nbsp; //directly with the main thread hence doesnt release the hand until forced to stop&nbsp; &nbsp; //For that we need to create it's own thread hence being able to play sound without freezing the remaining of the app&nbsp; &nbsp; //private Handler myHandler&nbsp; &nbsp; @Override&nbsp; &nbsp; protected void onCreate(Bundle savedInstanceState) {&nbsp; &nbsp; &nbsp; &nbsp; super.onCreate(savedInstanceState);&nbsp; &nbsp; &nbsp; &nbsp; setContentView(R.layout.activity_activity_main);&nbsp; &nbsp; &nbsp; &nbsp; //Handler&nbsp; &nbsp; &nbsp; &nbsp; //Route the sound to the AUX only and always&nbsp; &nbsp; &nbsp; &nbsp; AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);&nbsp; &nbsp; &nbsp; &nbsp; audioManager.setMode(AudioManager.MODE_IN_CALL);&nbsp; &nbsp; &nbsp; &nbsp; audioManager.setSpeakerphoneOn(false);&nbsp; &nbsp; &nbsp; &nbsp; audioManager.setWiredHeadsetOn(true);&nbsp; &nbsp; &nbsp; &nbsp; audioManager.setBluetoothScoOn(false);&nbsp; &nbsp; &nbsp; &nbsp; final playerTask pl_task = new playerTask();&nbsp; &nbsp; &nbsp; /////Use a toggle button to start or stop the recording///You could use anything&nbsp; &nbsp; &nbsp; &nbsp; onOff = (ToggleButton)findViewById(R.id.OnOff);&nbsp; &nbsp; &nbsp; &nbsp; onOff.setTextOff("PLAY");&nbsp; &nbsp; &nbsp; &nbsp; onOff.setTextOn("STOP");&nbsp; &nbsp; &nbsp; &nbsp; onOff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void onCheckedChanged(CompoundButton buttonview, boolean isCheked){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Running thread&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (isCheked){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; messagefield.setText("Playing");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pl_task.execTask();&nbsp; ///Start streaming&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; messagefield.setText("Not Playing");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pl_task.abortTask();&nbsp; ///Stop streaming&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });}这些是您需要请求的权限:&nbsp; &nbsp;<uses-permission android:name="android.permission.RECORD_AUDIO" /><uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java