如何在我的无线电应用程序中使用Phonestatelistener控制媒体声音

时间:2012-03-10 13:48:49

标签: android

有人可以帮我实现Phonestatelistener来控制我的应用程序在接听电话和通话期间的媒体声音吗?如果有人正在打电话,我正在从我的应用程序收听我的电台,它想要静音当前的声音。对我来说,最好的解决方案是在通话期间“静音”声音而不是停止。

到目前为止,我发现我需要 PhoneStateListener TelephonyManager

在AndroidManifest.xml中

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>

现在我的 MyRadio.java 有什么我需要放的地方?

package com.radiob.myradio;

import android.app.Activity;
import android.app.AlertDialog;

import com.google.ads.*;
import com.spoledge.aacplayer.AACFileChunkPlayer;
import com.spoledge.aacplayer.AACPlayer;
import com.spoledge.aacplayer.ArrayAACPlayer;
import com.spoledge.aacplayer.ArrayDecoder;
import com.spoledge.aacplayer.Decoder;
import com.spoledge.aacplayer.History;
import com.spoledge.aacplayer.PlayerCallback;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;

import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.MessageQueue.IdleHandler;
import android.util.Log;
import android.view.View;

import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;



// This is the main activity.

public class MyRadio extends Activity implements View.OnClickListener, PlayerCallback {

private History history;
private AutoCompleteTextView urlView;
private Button btnFaad2;
private Button btnFFmpeg;
private Button btnOpenCORE;
private Button btnMMSWMA;
private Button btnStop;
private TextView txtStatus;
private TextView txtPlayStatus;
private EditText txtBufAudio;
private EditText txtBufDecode;
private ProgressBar progress;
private Handler uiHandler;
private AudioManager mAudioManager;



    // Decoder features
private int dfeatures;

private AACPlayer aacPlayer;
private AACFileChunkPlayer aacFileChunkPlayer;


    ////////////////////////////////////////////////////////////////////////////
    // PlayerCallback
    ////////////////////////////////////////////////////////////////////////////

    private boolean playerStarted;

    public void playerStarted() {
        uiHandler.post( new Runnable() {
            public void run() {
                txtBufAudio.setEnabled( false );
                txtBufDecode.setEnabled( false );
                btnFaad2.setEnabled( false );
                btnFFmpeg.setEnabled( false );
                btnOpenCORE.setEnabled( false );
                btnMMSWMA.setEnabled( false );
                btnStop.setEnabled( true );

                txtPlayStatus.setText( R.string.text_buffering );
                progress.setProgress( 0 );
                progress.setVisibility( View.VISIBLE );

                playerStarted = true;
            }
        });
    }





    /**
     * This method is called periodically by PCMFeed.
     *
     * @param isPlaying false means that the PCM data are being buffered,
     *          but the audio is not playing yet
     *
     * @param audioBufferSizeMs the buffered audio data expressed in milliseconds of playing
     * @param audioBufferCapacityMs the total capacity of audio buffer expressed in milliseconds of playing
     */
    public void playerPCMFeedBuffer( final boolean isPlaying,
                                     final int audioBufferSizeMs, final int audioBufferCapacityMs ) {

        uiHandler.post( new Runnable() {
            public void run() {
                progress.setProgress( audioBufferSizeMs * progress.getMax() / audioBufferCapacityMs );
                if (isPlaying) txtPlayStatus.setText( R.string.text_playing );
            }
        });
    }


    public void playerStopped( final int perf ) {
        uiHandler.post( new Runnable() {
            public void run() {
                enableButtons();
                btnStop.setEnabled( false );
                txtBufAudio.setEnabled( true );
                txtBufDecode.setEnabled( true );
                txtStatus.setText( R.string.text_stopped );
                txtPlayStatus.setText( "" + perf + " %" );
                progress.setVisibility( View.INVISIBLE );

                playerStarted = false;
            }
        });
    }


    public void playerException( final Throwable t) {
        uiHandler.post( new Runnable() {
            public void run() {
                new AlertDialog.Builder( MyRadio.this )
                    .setTitle( R.string.text_exception )
                    .setMessage( t.toString())
                    .setNeutralButton( R.string.button_close,
                        new DialogInterface.OnClickListener() {
                            public void onClick( DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        }
                     )
                    .show();

                txtStatus.setText( R.string.text_stopped );

                if (playerStarted) playerStopped( 0 );
            }
        });
    }


    ////////////////////////////////////////////////////////////////////////////
    // OnClickListener
    ////////////////////////////////////////////////////////////////////////////

    /**
     * Called when a view has been clicked.
     */
    public void onClick( View v ) {
        try {
            switch (v.getId()) {

                case R.id.view_main_button_faad2:
                    start( Decoder.DECODER_FAAD2 );
                    txtStatus.setText( R.string.text_using_FAAD2 );
                    break; 

                case R.id.view_main_button_ffmpeg:
                    start( Decoder.DECODER_FFMPEG );
                    txtStatus.setText( R.string.text_using_FFmpeg );
                    break; 

                case R.id.view_main_button_opencore:
                    start( Decoder.DECODER_OPENCORE );
                    txtStatus.setText( R.string.text_using_OpenCORE );
                    break; 

                case R.id.view_main_button_mmswma:
                    start( Decoder.DECODER_FFMPEG_WMA );
                    txtStatus.setText( R.string.text_using_MMSWMA );
                    break; 

                /*
                case R.id.view_main_button_file:
                    stop();
                    aacFileChunkPlayer = new AACFileChunkPlayer( getUrl(), 8000, 8000 );
                    aacFileChunkPlayer.start();
                    txtStatus.setText( R.string.text_using_file_chunks );
                    break;
                */

                case R.id.view_main_button_stop:
                    stop();
                    break;
            }
        }
        catch (Exception e) {
            Log.e( "MyRadio", "exc" , e );
        }
    }


    ////////////////////////////////////////////////////////////////////////////
    // Protected
    ////////////////////////////////////////////////////////////////////////////

    @Override
    protected void onCreate( Bundle savedInstanceState ) {
        super.onCreate( savedInstanceState );

        setContentView( R.layout.main );


      // volume
      final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
      int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
      int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
      SeekBar volControl = (SeekBar)findViewById(R.id.volbar);
      volControl.setMax(maxVolume);
      volControl.setProgress(curVolume);
      volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

  public void onStopTrackingTouch(SeekBar arg0) {
   // TODO Auto-generated method stub

  }

  public void onStartTrackingTouch(SeekBar arg0) {
   // TODO Auto-generated method stub

  }

  public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
   // TODO Auto-generated method stub
   audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
  }
 });

        // 




        btnFaad2 = (Button) findViewById( R.id.view_main_button_faad2 );
        btnFFmpeg = (Button) findViewById( R.id.view_main_button_ffmpeg );
        btnOpenCORE = (Button) findViewById( R.id.view_main_button_opencore );
        btnMMSWMA = (Button) findViewById( R.id.view_main_button_mmswma );
        //Button b3 = (Button) findViewById( R.id.view_main_button_file );
        btnStop = (Button) findViewById( R.id.view_main_button_stop );

        urlView = (AutoCompleteTextView) findViewById( R.id.view_main_edit_url );
        txtStatus = (TextView) findViewById( R.id.view_main_text_what );
        txtPlayStatus = (TextView) findViewById( R.id.view_main_text_status );
        txtBufAudio = (EditText) findViewById( R.id.view_main_text_bufaudio );
        txtBufDecode = (EditText) findViewById( R.id.view_main_text_bufdecode );

        progress = (ProgressBar) findViewById( R.id.view_main_progress );

        txtBufAudio.setText( String.valueOf( AACPlayer.DEFAULT_AUDIO_BUFFER_CAPACITY_MS ));
        txtBufDecode.setText( String.valueOf( AACPlayer.DEFAULT_DECODE_BUFFER_CAPACITY_MS ));

        btnFaad2.setOnClickListener( this );
        btnFFmpeg.setOnClickListener( this );
        btnOpenCORE.setOnClickListener( this );
        btnMMSWMA.setOnClickListener( this );
        //b3.setOnClickListener( this );
        btnStop.setOnClickListener( this );

        dfeatures = ArrayDecoder.getFeatures();

        enableButtons();

        history = new History( this );
        history.read();

        if (history.size() == 0 ) {
            history.addUrl( "/sdcard/local/cro" );
        }

        urlView.setAdapter( history.getArrayAdapter());
        uiHandler = new Handler();
    }


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


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stop();
    }


    ////////////////////////////////////////////////////////////////////////////
    // Private
    ////////////////////////////////////////////////////////////////////////////

    private void start( int decoder ) {
        stop();
        aacPlayer = new ArrayAACPlayer( ArrayDecoder.create( decoder ), this,
                                        getInt( txtBufAudio ), getInt( txtBufDecode ));
        aacPlayer.playAsync( getUrl());
    }


    private void stop() {
        if (aacFileChunkPlayer != null) { aacFileChunkPlayer.stop(); aacFileChunkPlayer = null; }
        if (aacPlayer != null) { aacPlayer.stop(); aacPlayer = null; }
    }


    private String getUrl() {
        String ret = urlView.getText().toString();

        history.addUrl( ret );

        return ret;
    }


    private void enableButtons() {
        if ((dfeatures & Decoder.DECODER_FAAD2) != 0) btnFaad2.setEnabled( true );
        if ((dfeatures & Decoder.DECODER_FFMPEG) != 0) btnFFmpeg.setEnabled( true );
        if ((dfeatures & Decoder.DECODER_OPENCORE) != 0) btnOpenCORE.setEnabled( true );
        if ((dfeatures & Decoder.DECODER_FFMPEG_WMA) != 0) btnMMSWMA.setEnabled( true );
    }


    private int getInt( EditText et ) {
        return Integer.parseInt( et.getText().toString());
    }


    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

    }

}

1 个答案:

答案 0 :(得分:2)

您可以改为使用PhoneStateListener,而不是使用AudioManager.requestAudioFocus。这将允许您告诉Android您正在使用特定的音频流,并且每当另一个应用程序想要播放音频时(例如当您的手机接到电话时),您将获得回调。然后,您可以选择停止播放,也可以暂停直到其他应用程序完成。举个例子:

AudioManager.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener() {
    @Override public void onAudioFocusChange(int reason) {

        switch (reason) {
            case AudioManager.AUDIOFOCUS_LOSS:
                // Lost focus, pause playback
                break;

            case AudioManager.AUDIOFOCUS_GAIN:
                // Gained focus, start playback
                break
        }
    }
});