简体   繁体   English

在另一个活动中播放媒体文件

[英]Playing media files in another activity

I have retrieved the songs present on my phone and when I click on the list item it switches to the next activity and plays the song. 我已经检索了手机上显示的歌曲,当我单击列表项时,它会切换到下一个活动并播放歌曲。

But when I go back to my playlist and click again on another song, the previous song is still being played as well as the song I just clicked. 但是,当我返回播放列表并再次单击另一首歌曲时,上一首歌曲仍在播放,就像我刚刚单击的歌曲一样。

Here is the code of Playlist.java : 这是Playlist.java的代码:

package com.example.padyplayer;

import java.io.IOException;
import java.util.ArrayList;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

 public class Playlist extends Activity implements OnItemClickListener {

ListView tracks_view;
ArrayList<String> songs;
ArrayAdapter<String> songs_items;
//MediaPlayer mediaplayer;
//AudioManager audiomanager;
Cursor cursor;
Uri uri;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_playlist);
    tracks_view = (ListView) findViewById(R.id.tracks);
    generate_Playlist();
    songs_items = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, songs);
    //mediaplayer = new MediaPlayer();
    //audiomanager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    tracks_view.setAdapter(songs_items);
    tracks_view.setOnItemClickListener(this); 

}

@SuppressWarnings("deprecation")
private void generate_Playlist() {
    // TODO Auto-generated method stub
    uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String projection[] = { android.provider.MediaStore.Audio.Media.DATA,
            android.provider.MediaStore.Audio.Media.TITLE,
            android.provider.MediaStore.Audio.Media.ARTIST,
            android.provider.MediaStore.Audio.Media.ALBUM,
            android.provider.MediaStore.Audio.Media.DURATION };
    cursor=this.managedQuery(uri, projection, null, null, null);
    songs=new ArrayList<String>();
    while(cursor.moveToNext())
    {
        songs.add(cursor.getString(1));
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.playlist, menu);
    return true;
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
    // TODO Auto-generated method stub
    //cursor.moveToPosition(position);
    int index1=position;
    Intent i=new Intent(getApplicationContext(),Controls.class);
    i.putExtra("index", index1);
    startActivity(i);

}

}

Here is the second class Controls.java : 这是第二类Controls.java

package com.example.padyplayer;

import java.io.IOException;
import java.util.ArrayList;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Controls extends Activity implements OnClickListener {

TextView song_view,artist_view;
Button play,next,back;
MediaPlayer mediaplayer=new MediaPlayer();
AudioManager audiomanager;
ArrayList<String> songs;
Cursor cursor;
Uri uri;
private int index=0;
//ArrayAdapter<String> song_items;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_controls);
    play=(Button)findViewById(R.id.play);
    next=(Button)findViewById(R.id.next);
    back=(Button)findViewById(R.id.back);
    play.setOnClickListener(this);
    next.setOnClickListener(this);
    back.setOnClickListener(this);
    //mediaplayer=new MediaPlayer();
    audiomanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
    getMusic();
    Bundle b=getIntent().getExtras();
    index = b.getInt("index");
    playSong(index);
}




@SuppressWarnings("deprecation")
private void getMusic() {
    // TODO Auto-generated method stub
    uri=android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String projection[]={android.provider.MediaStore.Audio.Media.DATA,
            android.provider.MediaStore.Audio.Media.TITLE,
            android.provider.MediaStore.Audio.Media.ARTIST,
            android.provider.MediaStore.Audio.Media.ALBUM,
            android.provider.MediaStore.Audio.Media.DURATION};
    cursor=this.managedQuery(uri, projection, null, null,null);
    songs=new ArrayList<String>();
    while (cursor.moveToNext()) {
        songs.add(cursor.getString(1));
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.controls, menu);
    return true;
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.play:
        if(mediaplayer.isPlaying())
        {
            mediaplayer.pause();
            play.setText("play");
        }
        else if(mediaplayer!=null)
        {
            mediaplayer.start();
            play.setText("pause");

        }
        break;
    case R.id.next:
        if(index<(songs.size()-1)){
            index+=1;
            playSong(index);
        }
        else
        {
            index=0;
            playSong(index);
        }
        break;
    case R.id.back:
        if(index>0){
            index-=1;
            playSong(index);
        }
        else
        {
            index=songs.size()-1;
            playSong(index);
        }
        break;


    default:
        break;
    }
    //

}

private void playSong(int index2) {
    // TODO Auto-generated method stub
    cursor.moveToPosition(index2);
    int song_id=cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
    String song_name=cursor.getString(song_id);

    try {
        mediaplayer.reset();
        mediaplayer.setDataSource(song_name);
        mediaplayer.prepare();
        mediaplayer.start();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

I'm stuck with this problem since two days. 自两天以来,我一直在解决这个问题。 Please help. 请帮忙。

My advice: use a Service to host the MediaPlayer and have your Activities communicate with the Service to play and stop songs. 我的建议:使用服务托管MediaPlayer,并使您的活动与服务进行通信以播放和停止歌曲。 Don't forget to call release on the MediaPlayer when you are done (if you use a new player for the next song). 完成后,别忘了在MediaPlayer上调用release(如果您在下一首歌曲中使用新的播放器)。

Edit: 编辑:

The Activity is not going to be the same instance each time it opens, and you create a new MediaPlayer each time an instance of the Activity is created. 每次打开时,Activity都不会是同一实例,并且每次创建Activity的实例时,都需要创建一个新的MediaPlayer。 Underneath the hood, there is a native object actually playing the music that is not intrinsically tied to the life cycle of the Activity, and you aren't calling stop or pause anywhere that would get called when Activities are changed. 在引擎盖下,有一个本地对象实际在播放音乐,该音乐本质上与Activity的生命周期无关,并且您不会在更改Activity时调用“ stop”或“ pause”。 You could potentially stop and release the MediaPlayer in an appropriate callback (onPause or onDestroy), but that will prevent you from playing music continuously. 您可能会在适当的回调(onPause或onDestroy)中停止并释放MediaPlayer,但这将阻止您连续播放音乐。 If you insist on using an Activity to host the MediaPlayer, then music playback has to be completely integrated into the life cycle of the Activity. 如果您坚持使用活动来托管MediaPlayer,则音乐播放必须完全集成到活动的生命周期中。 When the Activity is changed, you need to stop and release its resources explicitly. 更改活动后,您需要明确停止并释放其资源。 If you put it in a Service, you won't have that limitation. 如果将其放在“服务”中,则不会受到限制。 You can manage one or more MediaPlayers ( note the setNextMediaPlayer method ) without them being tied to any particular Activity. 您可以管理一个或多个MediaPlayers( 请注意setNextMediaPlayer方法 ),而不必将它们绑定到任何特定的Activity。

it will keep playing. 它会继续播放。 You need to free your media player object when you press back button. 当您按下后退按钮时,您需要释放媒体播放器对象。 In onPause(), release your media player object otherwise it will keep playing. 在onPause()中,释放您的媒体播放器对象,否则它将继续播放。

To implement music player, you can refer open source code. 要实现音乐播放器,您可以参考开源代码。 Refer VLC player source code. 请参阅VLC播放器源代码。

每次从mMediaPlayer.reset()开始播放歌曲之前,您都可以每次播放新歌曲,或者检查是否正在播放mediaplayer,如果停止播放

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM