Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/190.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 我创建了一个歌曲播放器,它具有播放、暂停等基本功能,但我想在下面介绍一个功能_Android_Android Layout_Android Xml_Android Audiomanager_Android Music Player - Fatal编程技术网

Android 我创建了一个歌曲播放器,它具有播放、暂停等基本功能,但我想在下面介绍一个功能

Android 我创建了一个歌曲播放器,它具有播放、暂停等基本功能,但我想在下面介绍一个功能,android,android-layout,android-xml,android-audiomanager,android-music-player,Android,Android Layout,Android Xml,Android Audiomanager,Android Music Player,我创建了一个在线广播播放器TuneUP,它具有播放、暂停等基本功能。当我单击播放列表时,将播放当前歌曲索引。现在,当歌曲播放时,我使用intent按下后退按钮转到我的家庭活动,歌曲仍在播放。但是,当我想点击播放器按钮转到播放器时,我的播放/暂停按钮的状态为“播放”,当我点击播放按钮时,我会在使用前向您提供我的代码示例加入此概念。plz帮助我如何在主屏幕上添加播放/暂停按钮以停止播放歌曲。我希望类似于此plz,请参见下图 主屏幕 public class MainActivity extends

我创建了一个在线广播播放器TuneUP,它具有播放、暂停等基本功能。当我单击播放列表时,将播放当前歌曲索引。现在,当歌曲播放时,我使用intent按下后退按钮转到我的家庭活动,歌曲仍在播放。但是,当我想点击播放器按钮转到播放器时,我的播放/暂停按钮的状态为“播放”,当我点击播放按钮时,我会在使用前向您提供我的代码示例加入此概念。plz帮助我如何在主屏幕上添加播放/暂停按钮以停止播放歌曲。我希望类似于此plz,请参见下图

主屏幕

public class MainActivity extends TabActivity {
String[] actions = new String[] { "Tune-Up", "About Us", "Like-Us",
        "Other", "Exit" };
Spinner country_list;
private TextView tv_radio_name;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    TabHost tabHost = getTabHost();
    TabSpec allcallspec = tabHost.newTabSpec("listner");
    allcallspec.setIndicator("listener");
    Intent allIntent = new Intent(this, Tab_Listner.class);
    allcallspec.setContent(allIntent);

    // Tab for recived call
    TabSpec recivespec = tabHost.newTabSpec("Like");
    // setting Title and Icon for the Tab
    recivespec.setIndicator("Like");
    Intent reciveIntent = new Intent(MainActivity.this, Tab_Like.class);
    recivespec.setContent(reciveIntent);

    TabSpec recivespec1 = tabHost.newTabSpec("Categery");
    // setting Title and Icon for the Tab
    recivespec1.setIndicator("CateGories");
    Intent reciveIntent1 = new Intent(MainActivity.this,
            Category_name.class);
    recivespec1.setContent(reciveIntent1);

    tabHost.addTab(recivespec);
    tabHost.addTab(allcallspec); // Adding photos tab
    // Adding songs tab

    tabHost.addTab(recivespec1); // Adding songs tab

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // MenuItem mainMenuSpinner = menu.findItem( R.id.menu_main_spinner);
    // setupMainMenuSpinner( mainMenuSpinner );
    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    Log.i("Device Versoin is", "" + currentapiVersion);
    if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        ActionBar actionBar = getActionBar();

        getMenuInflater().inflate(R.menu.mainactivity, menu);

        Log.i("Android Version is", "Belove Froyo Action Bar Not Displayed");
        MenuItem statusSpinner = menu.findItem(R.id.menu_status_spinner);
        setupStatusSpinner(statusSpinner);
    }

    return super.onCreateOptionsMenu(menu);
}

private void setupStatusSpinner(MenuItem item) {
    View view = item.getActionView();
    if (view instanceof Spinner) {
        Spinner spinner = (Spinner) view;
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getBaseContext(),
                android.R.layout.simple_spinner_dropdown_item, actions);

        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                switch (arg2) {
                case 1:
                    Log.i("About US", "Go");
                    startActivity(new Intent(MainActivity.this,
                            About_Us.class));
                    break;
                case 2:
                    String url = "https://www.facebook.com/musicbreeds";
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    startActivity(i);
                    break;
                case 3:
                    Log.i("Other", "Go");
                    startActivity(new Intent(MainActivity.this, Other.class));
                    break;
                case 4:
                    Log.i("Exit", "unSuccess");
                    System.out.print("not.......................");
                    System.exit(0);

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });
    }

}

}
public class Tab_Like extends Activity {

ListView lv;
TextView t1, t2;
ImageView iv;
public static String name, rating, like, radio_url, id, listner, image;
private ProgressDialog dialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    // super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.category_name_radio);

    setProgressBarIndeterminateVisibility(true);
    setProgressBarIndeterminateVisibility(false);
    super.onCreate(savedInstanceState);
    TextView tv = (TextView) findViewById(R.id.textView1);
    lv = (ListView) findViewById(R.id.list_view);
    t1 = (TextView) findViewById(R.id.tv_country);
    t2 = (TextView) findViewById(R.id.tv_country_details);
    iv = (ImageView) findViewById(R.id.iv_flag);
    // URL to the JSON data
    String strUrl = "http://vaibhavtech.com/work/android/json_radio.php?cat=like";
    // Creating a new non-ui thread task to download json data
    DownloadTask downloadTask = new DownloadTask();

    // Starting the download process
    downloadTask.execute(strUrl);

    // Getting a reference to ListView of activity_main

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            int songIndex = arg2;
            Intent intent = new Intent(Tab_Like.this, Play_Radio.class);
            intent.putExtra("songIndex", songIndex);
            setResult(100, intent);

            radio_url = ((TextView) arg1
                    .findViewById(R.id.tv_other_data_radio_url)).getText()
                    .toString();
            rating = ((TextView) arg1
                    .findViewById(R.id.tv_other_data_rating)).getText()
                    .toString();
            id = ((TextView) arg1.findViewById(R.id.tv_other_data_id))
                    .getText().toString();
            name = ((TextView) arg1.findViewById(R.id.tv_other_data_name))
                    .getText().toString();
            Tab_Listner.id = id;
            Tab_Listner.radio_url = radio_url;
            Tab_Listner.name = name;
            Tab_Listner.rating = rating;

            startActivity(intent);

        }

    });

}

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        exitByBackKey();

        // moveTaskToBack(false);

        return true;
    }
    return super.onKeyDown(keyCode, event);
}

protected void exitByBackKey() {

    AlertDialog alertbox = new AlertDialog.Builder(this)
            .setMessage("Do you want to exit application?")
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        // do something when the button is clicked
                        public void onClick(DialogInterface arg0, int arg1) {

                            Intent intent = new Intent(Intent.ACTION_MAIN);
                            intent.addCategory(Intent.CATEGORY_HOME);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            finish();
                            System.exit(0);
                            // close();

                        }
                    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {

                // do something when the button is clicked
                public void onClick(DialogInterface arg0, int arg1) {
                }
            }).show();

}

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    try {
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                iStream));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    } catch (Exception e) {
        Log.d("Exception while downloading url", e.toString());
    } finally {
        iStream.close();
    }

    return data;
}

/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String> {
    String data = null;

    // LinearLayout linlaHeaderProgress = (LinearLayout)
    // findViewById(R.id.linlaH);

    @Override
    protected void onPreExecute() {
        // SHOW THE SPINNER WHILE LOADING FEEDS
        // linlaHeaderProgress.setVisibility(View.VISIBLE);
        super.onPreExecute();
        dialog = ProgressDialog.show(Tab_Like.this, "", "Loading...", true);
    }

    @Override
    protected String doInBackground(String... url) {
        try {
            data = downloadUrl(url[0]);

        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // The parsing of the xml data is done in a non-ui thread
        ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
        listViewLoaderTask.execute(result);

    }

}

/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends
        AsyncTask<String, Void, SimpleAdapter> {

    JSONObject jObject;

    // Doing the parsing of xml data in a non-ui thread
    @Override
    protected SimpleAdapter doInBackground(String... strJson) {
        try {
            jObject = new JSONObject(strJson[0]);
            StarterParser countryJsonParser = new StarterParser();
            countryJsonParser.parse(jObject);
        } catch (Exception e) {
            Log.d("JSON Exception1", e.toString());
        }

        // Instantiating json parser class
        StarterParser countryJsonParser = new StarterParser();

        // A list object to store the parsed countries list
        List<HashMap<String, Object>> countries = null;

        try {
            // Getting the parsed data as a List construct
            countries = countryJsonParser.parse(jObject);
        } catch (Exception e) {
            Log.d("Exception", e.toString());
        }

        // Keys used in Hashmap

        String[] from = { "image", "id", "like", "rating", "listener",
                "radio_url", "name" };

        // Ids of views in listview_layout
        int[] to = { R.id.iv_other_data_image, R.id.tv_other_data_id,
                R.id.tv_other_data_like, R.id.tv_other_data_rating,
                R.id.tv_other_data_listner, R.id.tv_other_data_radio_url,
                R.id.tv_other_data_name };

        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
                countries, R.layout.lv_radio_detail, from, to);

        return adapter;
    }

    /** Invoked by the Android on "doInBackground" is executed */
    @Override
    protected void onPostExecute(SimpleAdapter adapter) {

        // Setting adapter for the listview
        if (dialog != null)
            dialog.dismiss();
        lv.setAdapter(adapter);

    }
}

}
public class Play_Radio extends Activity {
private ImageView playButton;
private TextView textStreamed, tv_radio_name, tv_radio_cat;
private boolean isPlaying;
private static StreamingMediaPlayer audioStreamer;
private AudioManager audioManager = null;
ImageView iv_like;
Dialog rankDialog;
RatingBar ratingBar, pre_rating;
float cus_rating;
AdView adView;
Dialog dialog;
public static String name, rating, like, radio_url, id, listner, image;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    setContentView(R.layout.play_radio);

    if (audioStreamer != null) {
        try {
            Log.i("Already ply", "Succss");
            audioStreamer.stop();

        } catch (Exception e) {
        }
    } else {
        Log.i("First time", "Play");

    }
    initControls();

}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    Log.i("On Pause is call", "Succcess");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    Log.i("Device Versoin is", "" + currentapiVersion);
    if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        ActionBar actionBar = getActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        getMenuInflater().inflate(R.menu.main, menu);
        Log.i("Android Device above", "Home Enbled");
    }

    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub

    switch (item.getItemId()) {
    case android.R.id.home:
        onBackPressed();
        return true;
    case R.id.home:
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        Log.i("Home", "Press");
        return true;

    }
    return super.onOptionsItemSelected(item);
}

private void initControls() {
    iv_like = (ImageView) findViewById(R.id.iv_activity_like);
    iv_like.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            v1.vibrate(40);
            Toast.makeText(getApplicationContext(),
                    "Thanks For like Our Station", Toast.LENGTH_LONG)
                    .show();

        }
    });
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    textStreamed = (TextView) findViewById(R.id.text_kb_streamed);

    playButton = (ImageView) findViewById(R.id.imageView1);
    playButton.setEnabled(false);
    playButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Log.i("Click sadg   ", "success");

            Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            v1.vibrate(40);
            if (audioStreamer.getMediaPlayer().isPlaying()) {
                Log.i("play ", "success");
                audioStreamer.getMediaPlayer().pause();
                playButton.setImageResource(R.drawable.play_radio_play);
            } else {
                Log.i("pause", "success");
                audioStreamer.getMediaPlayer().start();
                audioStreamer.startPlayProgressUpdater();
                playButton.setImageResource(R.drawable.play_radio_pause);
            }
            isPlaying = !isPlaying;
        }
    });

    // rating radio sation

    ImageView rankBtn = (ImageView) findViewById(R.id.iv_activity_rating);
    rankBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            rankDialog = new Dialog(Play_Radio.this,
                    R.style.FullHeightDialog);
            rankDialog.setContentView(R.layout.rating_bar);
            rankDialog.setCancelable(true);
            ratingBar = (RatingBar) rankDialog
                    .findViewById(R.id.dialog_ratingbar);
            float userRankValue = 0;
            // ratingBar.setRating(userRankValue);
            ratingBar
                    .setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
                        @Override
                        public void onRatingChanged(RatingBar ratingBar,
                                float rating, boolean fromUser) {
                            // TODO Auto-generated method stub
                            cus_rating = rating;

                        }
                    });

            Button updateButton = (Button) rankDialog
                    .findViewById(R.id.rank_dialog_button);
            updateButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(Play_Radio.this,
                            "Thanks For Rating Our Stations",
                            Toast.LENGTH_LONG).show();
                    rankDialog.dismiss();
                }
            });
            // now that the dialog is set up, it's time to show it
            rankDialog.show();
        }
    });

    String urlstring2 = Tab_Listner.radio_url;
    Toast.makeText(Play_Radio.this, "Please Wait...", Toast.LENGTH_LONG)
            .show();

    startStreamingAudio(urlstring2);
    tv_radio_cat = (TextView) findViewById(R.id.tv_play_radio_cat);
    tv_radio_name = (TextView) findViewById(R.id.tv_play_radio_name);
    tv_radio_name.setText(Tab_Listner.name);
    pre_rating = (RatingBar) findViewById(R.id.ratingBar1);
    pre_rating.setRating(Float.parseFloat(Tab_Listner.rating));
}

private void startStreamingAudio(String urlstring) {
    try {
        dialog = new Dialog(Play_Radio.this,
                android.R.style.Theme_Translucent_NoTitleBar);
        dialog.setContentView(R.layout.progress_layout);
        dialog.setTitle("loading...");
        dialog.show();
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        if (audioStreamer != null) {
            audioStreamer.interrupt();
        }
        audioStreamer = new StreamingMediaPlayer(this, textStreamed,
                playButton, progressBar, dialog);
        audioStreamer.startStreaming(urlstring, 5208, 216);

        // streamButton.setEnabled(false);
        // playButton.setEnabled(true);
    } catch (Exception e) {
        Log.e(getClass().getName(), "Error starting to stream audio.", e);
    }

}

public void onItemSelected(AdapterView parent, View v, int position, long id) {
    mSwitcher.setImageResource(mImageIds[position]);
}

public void onNothingSelected(AdapterView parent) {
}

public View makeView() {
    ImageView i = new ImageView(this);
    i.setBackgroundColor(0xFF000000);
    i.setScaleType(ImageView.ScaleType.FIT_CENTER);
    i.setLayoutParams(new ImageSwitcher.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    return i;
}

private ImageSwitcher mSwitcher;

public class ImageAdapter extends BaseAdapter {
    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return mThumbIds.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView i = new ImageView(mContext);

        i.setImageResource(mThumbIds[position]);
        i.setAdjustViewBounds(true);
        i.setLayoutParams(new Gallery.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        i.setBackgroundResource(R.drawable.picture_frame);
        return i;
    }

    private Context mContext;

}

private Integer[] mThumbIds = { R.drawable.calculator, R.drawable.calendar,
        R.drawable.camera };

private Integer[] mImageIds = { R.drawable.calculator, R.drawable.calendar,
        R.drawable.camera };

}
public class StreamingMediaPlayer {
private static final int INTIAL_KB_BUFFER = 96 * 10 / 8;// assume
// 96kbps*10secs/8bits
// per byte

private TextView textStreamed;

private ImageView playButton;

private Dialog dialog;
private ProgressBar progressBar;
// Track for display by progressBar
private long mediaLengthInKb, mediaLengthInSeconds;

private int totalKbRead = 0;

// Create Handler to call View updates on the main UI thread.
private final Handler handler = new Handler();

private MediaPlayer mediaPlayer;

private File downloadingMediaFile;

private boolean isInterrupted;

private Context context;

private int counter = 0;

public StreamingMediaPlayer(Context context, TextView textStreamed,
        ImageView playButton, ProgressBar progressBar, Dialog dialog) {
    this.context = context;
    this.textStreamed = textStreamed;
    this.playButton = playButton;
    this.progressBar = progressBar;
    this.dialog = dialog;
}

/**
 * Progressivly download the media to a temporary location and update the
 * MediaPlayer as new content becomes available.
 */
public void startStreaming(final String mediaUrl, long mediaLengthInKb,
        long mediaLengthInSeconds) throws IOException {

    this.mediaLengthInKb = mediaLengthInKb;
    this.mediaLengthInSeconds = mediaLengthInSeconds;

    Runnable r = new Runnable() {
        public void run() {
            // Dialog dialog=null;
            try {
                downloadAudioIncrement(mediaUrl);

            } catch (IOException e) {
                Log.e(getClass().getName(),
                        "Unable to initialize the MediaPlayer for fileUrl="
                                + mediaUrl, e);
                return;
            }
        }
    };
    new Thread(r).start();

}

/**
 * Download the url stream to a temporary location and then call the
 * setDataSource for that local file
 */
public void downloadAudioIncrement(String mediaUrl) throws IOException {

    URLConnection cn = new URL(mediaUrl).openConnection();
    cn.connect();
    InputStream stream = cn.getInputStream();
    if (stream == null) {
        Log.e(getClass().getName(),
                "Unable to create InputStream for mediaUrl:" + mediaUrl);
    }

    downloadingMediaFile = new File(context.getCacheDir(),
            "downloadingMedia.dat");
    if (downloadingMediaFile.exists()) {
        downloadingMediaFile.delete();
    }

    FileOutputStream out = new FileOutputStream(downloadingMediaFile);
    byte buf[] = new byte[16384];
    int totalBytesRead = 0, incrementalBytesRead = 0;
    do {
        int numread = stream.read(buf);
        if (numread <= 0)
            break;
        out.write(buf, 0, numread);
        totalBytesRead += numread;
        incrementalBytesRead += numread;
        totalKbRead = totalBytesRead / 1000;

        testMediaBuffer();
        fireDataLoadUpdate();
    } while (validateNotInterrupted());
    stream.close();
    if (validateNotInterrupted()) {
        fireDataFullyLoaded();
    }
}

private boolean validateNotInterrupted() {
    if (isInterrupted) {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
            // mediaPlayer.release();
        }
        return false;
    } else {
        return true;
    }
}

private void testMediaBuffer() {
    Runnable updater = new Runnable() {
        public void run() {
            if (mediaPlayer == null) {
                // Only create the MediaPlayer once we have the minimum
                // buffered data
                if (totalKbRead >= INTIAL_KB_BUFFER) {
                    try {
                        startMediaPlayer();
                    } catch (Exception e) {
                        Log.e(getClass().getName(),
                                "Error copying buffered conent.", e);
                    }
                }
            } else if (mediaPlayer.getDuration()
                    - mediaPlayer.getCurrentPosition() <= 1000) {
                transferBufferToMediaPlayer();
            }
        }
    };
    handler.post(updater);
}

private void startMediaPlayer() {
    try {
        File bufferedFile = new File(context.getCacheDir(), "playingMedia"
                + (counter++) + ".dat");

        moveFile(downloadingMediaFile, bufferedFile);

        Log.e(getClass().getName(),
                "Buffered File path: " + bufferedFile.getAbsolutePath());
        Log.e(getClass().getName(),
                "Buffered File length: " + bufferedFile.length() + "");

        mediaPlayer = createMediaPlayer(bufferedFile);

        // We have pre-loaded enough content and started the MediaPlayer so
        // update the buttons & progress meters.
        mediaPlayer.start();
        startPlayProgressUpdater();
        playButton.setEnabled(true);
    } catch (IOException e) {
        Log.e(getClass().getName(), "Error initializing the MediaPlayer.",
                e);
        return;
    }
}

private MediaPlayer createMediaPlayer(File mediaFile) throws IOException {
    MediaPlayer mPlayer = new MediaPlayer();
    mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        public boolean onError(MediaPlayer mp, int what, int extra) {
            Log.e(getClass().getName(), "Error in MediaPlayer: (" + what
                    + ") with extra (" + extra + ")");
            return false;
        }
    });
    FileInputStream fis = new FileInputStream(mediaFile);
    mPlayer.setDataSource(fis.getFD());
    mPlayer.prepare();
    return mPlayer;
}

private void transferBufferToMediaPlayer() {
    try {
        // First determine if we need to restart the player after
        // transferring data...e.g. perhaps the user pressed pause
        boolean wasPlaying = mediaPlayer.isPlaying();
        int curPosition = mediaPlayer.getCurrentPosition();
        // Copy the currently downloaded content to a new buffered File.
        // Store the old File for deleting later.
        File oldBufferedFile = new File(context.getCacheDir(),
                "playingMedia" + counter + ".dat");
        File bufferedFile = new File(context.getCacheDir(), "playingMedia"
                + (counter++) + ".dat");

        // This may be the last buffered File so ask that it be delete on
        // exit. If it's already deleted, then this won't mean anything. If
        // you want to
        // keep and track fully downloaded files for later use, write
        // caching code and please send me a copy.
        bufferedFile.deleteOnExit();
        moveFile(downloadingMediaFile, bufferedFile);
        mediaPlayer.pause();
        mediaPlayer = createMediaPlayer(bufferedFile);
        mediaPlayer.seekTo(curPosition);

        boolean atEndOfFile = mediaPlayer.getDuration()
                - mediaPlayer.getCurrentPosition() <= 1000;
        if (wasPlaying || atEndOfFile) {
            mediaPlayer.start();
        }
        oldBufferedFile.delete();

    } catch (Exception e) {
        Log.e(getClass().getName(),
                "Error updating to newly loaded content.", e);
    }
}

private void fireDataLoadUpdate() {
    Runnable updater = new Runnable() {
        public void run() {
            textStreamed.setText((totalKbRead + "Kb"));
            float loadProgress = ((float) totalKbRead / (float) mediaLengthInKb);
            progressBar.setSecondaryProgress((int) (loadProgress * 100));
            if (dialog != null)
                dialog.dismiss();
        }
    };
    handler.post(updater);
}

private void fireDataFullyLoaded() {
    Runnable updater = new Runnable() {
        public void run() {
            transferBufferToMediaPlayer();

            // Delete the downloaded File as it's now been transferred to
            // the currently playing buffer file.
            downloadingMediaFile.delete();
            textStreamed
                    .setText(("Audio full loaded: " + totalKbRead + " Kb read"));
        }
    };
    handler.post(updater);
}

public MediaPlayer getMediaPlayer() {
    return mediaPlayer;
}

public void startPlayProgressUpdater() {
    float progress = (((float) mediaPlayer.getCurrentPosition() / 1000) / mediaLengthInSeconds);
    progressBar.setProgress((int) (progress * 100));
    if (dialog != null)
        dialog.dismiss();
    if (mediaPlayer.isPlaying()) {
        Runnable notification = new Runnable() {
            public void run() {
                startPlayProgressUpdater();
            }
        };
        handler.postDelayed(notification, 1000);
    }
}

public void interrupt() {
    playButton.setEnabled(false);
    isInterrupted = true;
    validateNotInterrupted();
}

/**
 * Move the file in oldLocation to newLocation.
 */
public void moveFile(File oldLocation, File newLocation) throws IOException {

    if (oldLocation.exists()) {
        BufferedInputStream reader = new BufferedInputStream(
                new FileInputStream(oldLocation));
        BufferedOutputStream writer = new BufferedOutputStream(
                new FileOutputStream(newLocation, false));
        try {
            // byte[] buff = new byte[8192];
            /* changing the size of the buffer */

            byte[] buff = new byte[16384];

            int numChars;
            while ((numChars = reader.read(buff, 0, buff.length)) != -1) {
                writer.write(buff, 0, numChars);
            }
        } catch (IOException ex) {
            throw new IOException("IOException when transferring "
                    + oldLocation.getPath() + " to "
                    + newLocation.getPath());
        } finally {
            try {
                if (reader != null) {
                    writer.close();
                    reader.close();
                }
            } catch (IOException ex) {
                Log.e(getClass().getName(),
                        "Error closing files when transferring "
                                + oldLocation.getPath() + " to "
                                + newLocation.getPath());
            }
        }
    } else {
        throw new IOException(
                "Old location does not exist when transferring "
                        + oldLocation.getPath() + " to "
                        + newLocation.getPath());
    }
}

public void change_volume(float vol) {
    Log.i("Media Player volume change", "Success" + vol);
    mediaPlayer.setVolume(vol, vol);
}

public void stop() {
    mediaPlayer.stop();
}

public void stoppreviousPlayer() {
    if (mediaPlayer.isPlaying()) {
        mediaPlayer.stop();
    }
}
}
streamingradioplay****************************************************

public class MainActivity extends TabActivity {
String[] actions = new String[] { "Tune-Up", "About Us", "Like-Us",
        "Other", "Exit" };
Spinner country_list;
private TextView tv_radio_name;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    TabHost tabHost = getTabHost();
    TabSpec allcallspec = tabHost.newTabSpec("listner");
    allcallspec.setIndicator("listener");
    Intent allIntent = new Intent(this, Tab_Listner.class);
    allcallspec.setContent(allIntent);

    // Tab for recived call
    TabSpec recivespec = tabHost.newTabSpec("Like");
    // setting Title and Icon for the Tab
    recivespec.setIndicator("Like");
    Intent reciveIntent = new Intent(MainActivity.this, Tab_Like.class);
    recivespec.setContent(reciveIntent);

    TabSpec recivespec1 = tabHost.newTabSpec("Categery");
    // setting Title and Icon for the Tab
    recivespec1.setIndicator("CateGories");
    Intent reciveIntent1 = new Intent(MainActivity.this,
            Category_name.class);
    recivespec1.setContent(reciveIntent1);

    tabHost.addTab(recivespec);
    tabHost.addTab(allcallspec); // Adding photos tab
    // Adding songs tab

    tabHost.addTab(recivespec1); // Adding songs tab

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // MenuItem mainMenuSpinner = menu.findItem( R.id.menu_main_spinner);
    // setupMainMenuSpinner( mainMenuSpinner );
    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    Log.i("Device Versoin is", "" + currentapiVersion);
    if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        ActionBar actionBar = getActionBar();

        getMenuInflater().inflate(R.menu.mainactivity, menu);

        Log.i("Android Version is", "Belove Froyo Action Bar Not Displayed");
        MenuItem statusSpinner = menu.findItem(R.id.menu_status_spinner);
        setupStatusSpinner(statusSpinner);
    }

    return super.onCreateOptionsMenu(menu);
}

private void setupStatusSpinner(MenuItem item) {
    View view = item.getActionView();
    if (view instanceof Spinner) {
        Spinner spinner = (Spinner) view;
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getBaseContext(),
                android.R.layout.simple_spinner_dropdown_item, actions);

        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                switch (arg2) {
                case 1:
                    Log.i("About US", "Go");
                    startActivity(new Intent(MainActivity.this,
                            About_Us.class));
                    break;
                case 2:
                    String url = "https://www.facebook.com/musicbreeds";
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    startActivity(i);
                    break;
                case 3:
                    Log.i("Other", "Go");
                    startActivity(new Intent(MainActivity.this, Other.class));
                    break;
                case 4:
                    Log.i("Exit", "unSuccess");
                    System.out.print("not.......................");
                    System.exit(0);

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });
    }

}

}
public class Tab_Like extends Activity {

ListView lv;
TextView t1, t2;
ImageView iv;
public static String name, rating, like, radio_url, id, listner, image;
private ProgressDialog dialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    // super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.category_name_radio);

    setProgressBarIndeterminateVisibility(true);
    setProgressBarIndeterminateVisibility(false);
    super.onCreate(savedInstanceState);
    TextView tv = (TextView) findViewById(R.id.textView1);
    lv = (ListView) findViewById(R.id.list_view);
    t1 = (TextView) findViewById(R.id.tv_country);
    t2 = (TextView) findViewById(R.id.tv_country_details);
    iv = (ImageView) findViewById(R.id.iv_flag);
    // URL to the JSON data
    String strUrl = "http://vaibhavtech.com/work/android/json_radio.php?cat=like";
    // Creating a new non-ui thread task to download json data
    DownloadTask downloadTask = new DownloadTask();

    // Starting the download process
    downloadTask.execute(strUrl);

    // Getting a reference to ListView of activity_main

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            int songIndex = arg2;
            Intent intent = new Intent(Tab_Like.this, Play_Radio.class);
            intent.putExtra("songIndex", songIndex);
            setResult(100, intent);

            radio_url = ((TextView) arg1
                    .findViewById(R.id.tv_other_data_radio_url)).getText()
                    .toString();
            rating = ((TextView) arg1
                    .findViewById(R.id.tv_other_data_rating)).getText()
                    .toString();
            id = ((TextView) arg1.findViewById(R.id.tv_other_data_id))
                    .getText().toString();
            name = ((TextView) arg1.findViewById(R.id.tv_other_data_name))
                    .getText().toString();
            Tab_Listner.id = id;
            Tab_Listner.radio_url = radio_url;
            Tab_Listner.name = name;
            Tab_Listner.rating = rating;

            startActivity(intent);

        }

    });

}

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        exitByBackKey();

        // moveTaskToBack(false);

        return true;
    }
    return super.onKeyDown(keyCode, event);
}

protected void exitByBackKey() {

    AlertDialog alertbox = new AlertDialog.Builder(this)
            .setMessage("Do you want to exit application?")
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        // do something when the button is clicked
                        public void onClick(DialogInterface arg0, int arg1) {

                            Intent intent = new Intent(Intent.ACTION_MAIN);
                            intent.addCategory(Intent.CATEGORY_HOME);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            finish();
                            System.exit(0);
                            // close();

                        }
                    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {

                // do something when the button is clicked
                public void onClick(DialogInterface arg0, int arg1) {
                }
            }).show();

}

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    try {
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                iStream));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    } catch (Exception e) {
        Log.d("Exception while downloading url", e.toString());
    } finally {
        iStream.close();
    }

    return data;
}

/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String> {
    String data = null;

    // LinearLayout linlaHeaderProgress = (LinearLayout)
    // findViewById(R.id.linlaH);

    @Override
    protected void onPreExecute() {
        // SHOW THE SPINNER WHILE LOADING FEEDS
        // linlaHeaderProgress.setVisibility(View.VISIBLE);
        super.onPreExecute();
        dialog = ProgressDialog.show(Tab_Like.this, "", "Loading...", true);
    }

    @Override
    protected String doInBackground(String... url) {
        try {
            data = downloadUrl(url[0]);

        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // The parsing of the xml data is done in a non-ui thread
        ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
        listViewLoaderTask.execute(result);

    }

}

/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends
        AsyncTask<String, Void, SimpleAdapter> {

    JSONObject jObject;

    // Doing the parsing of xml data in a non-ui thread
    @Override
    protected SimpleAdapter doInBackground(String... strJson) {
        try {
            jObject = new JSONObject(strJson[0]);
            StarterParser countryJsonParser = new StarterParser();
            countryJsonParser.parse(jObject);
        } catch (Exception e) {
            Log.d("JSON Exception1", e.toString());
        }

        // Instantiating json parser class
        StarterParser countryJsonParser = new StarterParser();

        // A list object to store the parsed countries list
        List<HashMap<String, Object>> countries = null;

        try {
            // Getting the parsed data as a List construct
            countries = countryJsonParser.parse(jObject);
        } catch (Exception e) {
            Log.d("Exception", e.toString());
        }

        // Keys used in Hashmap

        String[] from = { "image", "id", "like", "rating", "listener",
                "radio_url", "name" };

        // Ids of views in listview_layout
        int[] to = { R.id.iv_other_data_image, R.id.tv_other_data_id,
                R.id.tv_other_data_like, R.id.tv_other_data_rating,
                R.id.tv_other_data_listner, R.id.tv_other_data_radio_url,
                R.id.tv_other_data_name };

        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
                countries, R.layout.lv_radio_detail, from, to);

        return adapter;
    }

    /** Invoked by the Android on "doInBackground" is executed */
    @Override
    protected void onPostExecute(SimpleAdapter adapter) {

        // Setting adapter for the listview
        if (dialog != null)
            dialog.dismiss();
        lv.setAdapter(adapter);

    }
}

}
public class Play_Radio extends Activity {
private ImageView playButton;
private TextView textStreamed, tv_radio_name, tv_radio_cat;
private boolean isPlaying;
private static StreamingMediaPlayer audioStreamer;
private AudioManager audioManager = null;
ImageView iv_like;
Dialog rankDialog;
RatingBar ratingBar, pre_rating;
float cus_rating;
AdView adView;
Dialog dialog;
public static String name, rating, like, radio_url, id, listner, image;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    setContentView(R.layout.play_radio);

    if (audioStreamer != null) {
        try {
            Log.i("Already ply", "Succss");
            audioStreamer.stop();

        } catch (Exception e) {
        }
    } else {
        Log.i("First time", "Play");

    }
    initControls();

}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    Log.i("On Pause is call", "Succcess");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    Log.i("Device Versoin is", "" + currentapiVersion);
    if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        ActionBar actionBar = getActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        getMenuInflater().inflate(R.menu.main, menu);
        Log.i("Android Device above", "Home Enbled");
    }

    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub

    switch (item.getItemId()) {
    case android.R.id.home:
        onBackPressed();
        return true;
    case R.id.home:
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        Log.i("Home", "Press");
        return true;

    }
    return super.onOptionsItemSelected(item);
}

private void initControls() {
    iv_like = (ImageView) findViewById(R.id.iv_activity_like);
    iv_like.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            v1.vibrate(40);
            Toast.makeText(getApplicationContext(),
                    "Thanks For like Our Station", Toast.LENGTH_LONG)
                    .show();

        }
    });
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    textStreamed = (TextView) findViewById(R.id.text_kb_streamed);

    playButton = (ImageView) findViewById(R.id.imageView1);
    playButton.setEnabled(false);
    playButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Log.i("Click sadg   ", "success");

            Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            v1.vibrate(40);
            if (audioStreamer.getMediaPlayer().isPlaying()) {
                Log.i("play ", "success");
                audioStreamer.getMediaPlayer().pause();
                playButton.setImageResource(R.drawable.play_radio_play);
            } else {
                Log.i("pause", "success");
                audioStreamer.getMediaPlayer().start();
                audioStreamer.startPlayProgressUpdater();
                playButton.setImageResource(R.drawable.play_radio_pause);
            }
            isPlaying = !isPlaying;
        }
    });

    // rating radio sation

    ImageView rankBtn = (ImageView) findViewById(R.id.iv_activity_rating);
    rankBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            rankDialog = new Dialog(Play_Radio.this,
                    R.style.FullHeightDialog);
            rankDialog.setContentView(R.layout.rating_bar);
            rankDialog.setCancelable(true);
            ratingBar = (RatingBar) rankDialog
                    .findViewById(R.id.dialog_ratingbar);
            float userRankValue = 0;
            // ratingBar.setRating(userRankValue);
            ratingBar
                    .setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
                        @Override
                        public void onRatingChanged(RatingBar ratingBar,
                                float rating, boolean fromUser) {
                            // TODO Auto-generated method stub
                            cus_rating = rating;

                        }
                    });

            Button updateButton = (Button) rankDialog
                    .findViewById(R.id.rank_dialog_button);
            updateButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(Play_Radio.this,
                            "Thanks For Rating Our Stations",
                            Toast.LENGTH_LONG).show();
                    rankDialog.dismiss();
                }
            });
            // now that the dialog is set up, it's time to show it
            rankDialog.show();
        }
    });

    String urlstring2 = Tab_Listner.radio_url;
    Toast.makeText(Play_Radio.this, "Please Wait...", Toast.LENGTH_LONG)
            .show();

    startStreamingAudio(urlstring2);
    tv_radio_cat = (TextView) findViewById(R.id.tv_play_radio_cat);
    tv_radio_name = (TextView) findViewById(R.id.tv_play_radio_name);
    tv_radio_name.setText(Tab_Listner.name);
    pre_rating = (RatingBar) findViewById(R.id.ratingBar1);
    pre_rating.setRating(Float.parseFloat(Tab_Listner.rating));
}

private void startStreamingAudio(String urlstring) {
    try {
        dialog = new Dialog(Play_Radio.this,
                android.R.style.Theme_Translucent_NoTitleBar);
        dialog.setContentView(R.layout.progress_layout);
        dialog.setTitle("loading...");
        dialog.show();
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        if (audioStreamer != null) {
            audioStreamer.interrupt();
        }
        audioStreamer = new StreamingMediaPlayer(this, textStreamed,
                playButton, progressBar, dialog);
        audioStreamer.startStreaming(urlstring, 5208, 216);

        // streamButton.setEnabled(false);
        // playButton.setEnabled(true);
    } catch (Exception e) {
        Log.e(getClass().getName(), "Error starting to stream audio.", e);
    }

}

public void onItemSelected(AdapterView parent, View v, int position, long id) {
    mSwitcher.setImageResource(mImageIds[position]);
}

public void onNothingSelected(AdapterView parent) {
}

public View makeView() {
    ImageView i = new ImageView(this);
    i.setBackgroundColor(0xFF000000);
    i.setScaleType(ImageView.ScaleType.FIT_CENTER);
    i.setLayoutParams(new ImageSwitcher.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    return i;
}

private ImageSwitcher mSwitcher;

public class ImageAdapter extends BaseAdapter {
    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return mThumbIds.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView i = new ImageView(mContext);

        i.setImageResource(mThumbIds[position]);
        i.setAdjustViewBounds(true);
        i.setLayoutParams(new Gallery.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        i.setBackgroundResource(R.drawable.picture_frame);
        return i;
    }

    private Context mContext;

}

private Integer[] mThumbIds = { R.drawable.calculator, R.drawable.calendar,
        R.drawable.camera };

private Integer[] mImageIds = { R.drawable.calculator, R.drawable.calendar,
        R.drawable.camera };

}
public class StreamingMediaPlayer {
private static final int INTIAL_KB_BUFFER = 96 * 10 / 8;// assume
// 96kbps*10secs/8bits
// per byte

private TextView textStreamed;

private ImageView playButton;

private Dialog dialog;
private ProgressBar progressBar;
// Track for display by progressBar
private long mediaLengthInKb, mediaLengthInSeconds;

private int totalKbRead = 0;

// Create Handler to call View updates on the main UI thread.
private final Handler handler = new Handler();

private MediaPlayer mediaPlayer;

private File downloadingMediaFile;

private boolean isInterrupted;

private Context context;

private int counter = 0;

public StreamingMediaPlayer(Context context, TextView textStreamed,
        ImageView playButton, ProgressBar progressBar, Dialog dialog) {
    this.context = context;
    this.textStreamed = textStreamed;
    this.playButton = playButton;
    this.progressBar = progressBar;
    this.dialog = dialog;
}

/**
 * Progressivly download the media to a temporary location and update the
 * MediaPlayer as new content becomes available.
 */
public void startStreaming(final String mediaUrl, long mediaLengthInKb,
        long mediaLengthInSeconds) throws IOException {

    this.mediaLengthInKb = mediaLengthInKb;
    this.mediaLengthInSeconds = mediaLengthInSeconds;

    Runnable r = new Runnable() {
        public void run() {
            // Dialog dialog=null;
            try {
                downloadAudioIncrement(mediaUrl);

            } catch (IOException e) {
                Log.e(getClass().getName(),
                        "Unable to initialize the MediaPlayer for fileUrl="
                                + mediaUrl, e);
                return;
            }
        }
    };
    new Thread(r).start();

}

/**
 * Download the url stream to a temporary location and then call the
 * setDataSource for that local file
 */
public void downloadAudioIncrement(String mediaUrl) throws IOException {

    URLConnection cn = new URL(mediaUrl).openConnection();
    cn.connect();
    InputStream stream = cn.getInputStream();
    if (stream == null) {
        Log.e(getClass().getName(),
                "Unable to create InputStream for mediaUrl:" + mediaUrl);
    }

    downloadingMediaFile = new File(context.getCacheDir(),
            "downloadingMedia.dat");
    if (downloadingMediaFile.exists()) {
        downloadingMediaFile.delete();
    }

    FileOutputStream out = new FileOutputStream(downloadingMediaFile);
    byte buf[] = new byte[16384];
    int totalBytesRead = 0, incrementalBytesRead = 0;
    do {
        int numread = stream.read(buf);
        if (numread <= 0)
            break;
        out.write(buf, 0, numread);
        totalBytesRead += numread;
        incrementalBytesRead += numread;
        totalKbRead = totalBytesRead / 1000;

        testMediaBuffer();
        fireDataLoadUpdate();
    } while (validateNotInterrupted());
    stream.close();
    if (validateNotInterrupted()) {
        fireDataFullyLoaded();
    }
}

private boolean validateNotInterrupted() {
    if (isInterrupted) {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
            // mediaPlayer.release();
        }
        return false;
    } else {
        return true;
    }
}

private void testMediaBuffer() {
    Runnable updater = new Runnable() {
        public void run() {
            if (mediaPlayer == null) {
                // Only create the MediaPlayer once we have the minimum
                // buffered data
                if (totalKbRead >= INTIAL_KB_BUFFER) {
                    try {
                        startMediaPlayer();
                    } catch (Exception e) {
                        Log.e(getClass().getName(),
                                "Error copying buffered conent.", e);
                    }
                }
            } else if (mediaPlayer.getDuration()
                    - mediaPlayer.getCurrentPosition() <= 1000) {
                transferBufferToMediaPlayer();
            }
        }
    };
    handler.post(updater);
}

private void startMediaPlayer() {
    try {
        File bufferedFile = new File(context.getCacheDir(), "playingMedia"
                + (counter++) + ".dat");

        moveFile(downloadingMediaFile, bufferedFile);

        Log.e(getClass().getName(),
                "Buffered File path: " + bufferedFile.getAbsolutePath());
        Log.e(getClass().getName(),
                "Buffered File length: " + bufferedFile.length() + "");

        mediaPlayer = createMediaPlayer(bufferedFile);

        // We have pre-loaded enough content and started the MediaPlayer so
        // update the buttons & progress meters.
        mediaPlayer.start();
        startPlayProgressUpdater();
        playButton.setEnabled(true);
    } catch (IOException e) {
        Log.e(getClass().getName(), "Error initializing the MediaPlayer.",
                e);
        return;
    }
}

private MediaPlayer createMediaPlayer(File mediaFile) throws IOException {
    MediaPlayer mPlayer = new MediaPlayer();
    mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        public boolean onError(MediaPlayer mp, int what, int extra) {
            Log.e(getClass().getName(), "Error in MediaPlayer: (" + what
                    + ") with extra (" + extra + ")");
            return false;
        }
    });
    FileInputStream fis = new FileInputStream(mediaFile);
    mPlayer.setDataSource(fis.getFD());
    mPlayer.prepare();
    return mPlayer;
}

private void transferBufferToMediaPlayer() {
    try {
        // First determine if we need to restart the player after
        // transferring data...e.g. perhaps the user pressed pause
        boolean wasPlaying = mediaPlayer.isPlaying();
        int curPosition = mediaPlayer.getCurrentPosition();
        // Copy the currently downloaded content to a new buffered File.
        // Store the old File for deleting later.
        File oldBufferedFile = new File(context.getCacheDir(),
                "playingMedia" + counter + ".dat");
        File bufferedFile = new File(context.getCacheDir(), "playingMedia"
                + (counter++) + ".dat");

        // This may be the last buffered File so ask that it be delete on
        // exit. If it's already deleted, then this won't mean anything. If
        // you want to
        // keep and track fully downloaded files for later use, write
        // caching code and please send me a copy.
        bufferedFile.deleteOnExit();
        moveFile(downloadingMediaFile, bufferedFile);
        mediaPlayer.pause();
        mediaPlayer = createMediaPlayer(bufferedFile);
        mediaPlayer.seekTo(curPosition);

        boolean atEndOfFile = mediaPlayer.getDuration()
                - mediaPlayer.getCurrentPosition() <= 1000;
        if (wasPlaying || atEndOfFile) {
            mediaPlayer.start();
        }
        oldBufferedFile.delete();

    } catch (Exception e) {
        Log.e(getClass().getName(),
                "Error updating to newly loaded content.", e);
    }
}

private void fireDataLoadUpdate() {
    Runnable updater = new Runnable() {
        public void run() {
            textStreamed.setText((totalKbRead + "Kb"));
            float loadProgress = ((float) totalKbRead / (float) mediaLengthInKb);
            progressBar.setSecondaryProgress((int) (loadProgress * 100));
            if (dialog != null)
                dialog.dismiss();
        }
    };
    handler.post(updater);
}

private void fireDataFullyLoaded() {
    Runnable updater = new Runnable() {
        public void run() {
            transferBufferToMediaPlayer();

            // Delete the downloaded File as it's now been transferred to
            // the currently playing buffer file.
            downloadingMediaFile.delete();
            textStreamed
                    .setText(("Audio full loaded: " + totalKbRead + " Kb read"));
        }
    };
    handler.post(updater);
}

public MediaPlayer getMediaPlayer() {
    return mediaPlayer;
}

public void startPlayProgressUpdater() {
    float progress = (((float) mediaPlayer.getCurrentPosition() / 1000) / mediaLengthInSeconds);
    progressBar.setProgress((int) (progress * 100));
    if (dialog != null)
        dialog.dismiss();
    if (mediaPlayer.isPlaying()) {
        Runnable notification = new Runnable() {
            public void run() {
                startPlayProgressUpdater();
            }
        };
        handler.postDelayed(notification, 1000);
    }
}

public void interrupt() {
    playButton.setEnabled(false);
    isInterrupted = true;
    validateNotInterrupted();
}

/**
 * Move the file in oldLocation to newLocation.
 */
public void moveFile(File oldLocation, File newLocation) throws IOException {

    if (oldLocation.exists()) {
        BufferedInputStream reader = new BufferedInputStream(
                new FileInputStream(oldLocation));
        BufferedOutputStream writer = new BufferedOutputStream(
                new FileOutputStream(newLocation, false));
        try {
            // byte[] buff = new byte[8192];
            /* changing the size of the buffer */

            byte[] buff = new byte[16384];

            int numChars;
            while ((numChars = reader.read(buff, 0, buff.length)) != -1) {
                writer.write(buff, 0, numChars);
            }
        } catch (IOException ex) {
            throw new IOException("IOException when transferring "
                    + oldLocation.getPath() + " to "
                    + newLocation.getPath());
        } finally {
            try {
                if (reader != null) {
                    writer.close();
                    reader.close();
                }
            } catch (IOException ex) {
                Log.e(getClass().getName(),
                        "Error closing files when transferring "
                                + oldLocation.getPath() + " to "
                                + newLocation.getPath());
            }
        }
    } else {
        throw new IOException(
                "Old location does not exist when transferring "
                        + oldLocation.getPath() + " to "
                        + newLocation.getPath());
    }
}

public void change_volume(float vol) {
    Log.i("Media Player volume change", "Success" + vol);
    mediaPlayer.setVolume(vol, vol);
}

public void stop() {
    mediaPlayer.stop();
}

public void stoppreviousPlayer() {
    if (mediaPlayer.isPlaying()) {
        mediaPlayer.stop();
    }
}
}
公共类流媒体播放器{
私有静态final int initial_KB_BUFFER=96*10/8;//假设
//96kbps*10秒/8比特
//每字节
私有文本视图文本流;
私有图像查看播放按钮;
私人对话;
私人ProgressBar ProgressBar;
//通过progressBar显示的曲目
私人长媒体长度ThinkB,媒体长度秒;
私有int totalKbRead=0;
//创建处理程序以在主UI线程上调用视图更新。
私有最终处理程序=新处理程序();
私人媒体播放器;
私有文件下载媒体文件;
私有布尔值中断;
私人语境;
专用整数计数器=0;
公共流媒体播放器(上下文、文本视图、文本流媒体、,
ImageView播放按钮、进度栏、进度栏、对话框){
this.context=上下文;
this.textStreamed=textStreamed;
this.playButton=playButton;
this.progressBar=progressBar;
this.dialog=dialog;
}
/**
*渐进地将媒体下载到临时位置并更新
*新内容可用时使用MediaPlayer。
*/
public void startStreaming(最终字符串mediaUrl,long mediaLengthInKb,
长媒体长度(秒)引发IOException{
this.mediaLengthInKb=mediaLengthInKb;
this.medialenghthinseconds=medialenghthinseconds;
Runnable r=新的Runnable(){
公开募捐{
//Dialog=null;
试一试{
下载音频增量(mediaUrl);
}捕获(IOE异常){
Log.e(getClass().getName(),
“无法为fileUrl=初始化MediaPlayer”
+mediaUrl,e);
返回;
}
}
};
新线程(r.start();
}
/**
*将url流下载到临时位置,然后调用
*该本地文件的setDataSource
*/
public void downloadAudioIncrement(字符串mediaUrl)引发IOException{
URLConnection cn=新URL(mediaUrl).openConnection();
cn.connect();
InputStream=cn.getInputStream();
if(流==null){
Log.e(getClass().getName(),
无法为mediaUrl创建输入流:“+mediaUrl”);
}
downloadingMediaFile=新文件(context.getCacheDir(),
“downloadingMedia.dat”);
if(下载MediaFile.exists()){
下载MediaFile.delete();
}
FileOutputStream out=新的FileOutputStream(下载MediaFile);
字节buf[]=新字节[16384];
int totalBytesRead=0,incrementalBytesRead=0;
做{
int numread=stream.read(buf);
if(numread=initial\u KB\u缓冲区){
试一试{
startMediaPlayer();
}捕获(例外e){
Log.e(getClass().getName(),
“复制缓冲内容时出错。”,e);
}
}
}else if(mediaPlayer.getDuration()

-getCurrentPosition()的想法是在发出新请求或单击播放按钮之前关闭现有媒体播放器

为此,您可以将mediPlayer对象设置为全局对象

public void onClick(View v)
{
    if (v == playButton)
    {
        playAudio();
    }
}

public void playAudio()
{
    mediaPlayer.stop();
    // then proceed with your new song playing code

}

我已经尝试过了,但它不起作用。你可以帮我吗?你正在停止媒体播放的当前实例,但它仍然播放歌曲??你可以在“主页”上的“播放暂停”按钮和当前播放歌曲的所有其他活动的底部检查“我想要这样”我不想要项目的完整代码,请给我一些时间,我会试着分析这个问题,如果我得到它,我一定会解决你的问题