同时在Media Player中播放超过1首歌曲

时间:2016-07-19 13:40:53

标签: android audio-player android-music-player

我是Android编程的新手,我正在尝试制作一个简单的媒体播放器应用程序,该应用程序从用户的SD卡中提取歌曲并使用户能够播放歌曲。我面临的问题是,在播放歌曲时,如果用户点击其他歌曲,该歌曲也会开始播放。

我搜索了解决方案并使用了release(),但问题仍然存在。

我很感激任何帮助!

相关代码:

using System;
using System.Collections.Generic;
using System.Windows;
using Microsoft.Practices.ServiceLocation;
using Prism.Unity;


namespace MyApp.Infrastructure.Services.Dialogs.WindowDialog
{
    public sealed class WindowDialogService : IWindowDialogService
    {
        private readonly List<Window> _openWindows = new List<Window>();
        private static volatile WindowDialogService _instance;
        private static readonly object SyncRoot = new Object();

        private WindowDialogService() { }

        public static WindowDialogService Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (SyncRoot)
                    {
                        if (_instance == null)
                            _instance = new WindowDialogService();
                    }
                }
                return _instance;
            }
        }


        public bool? ShowDialog<T>(Action onDialogClosed) where T : Window
        {
            try
            {
                 using (var container = new Microsoft.Practices.Unity.UnityContainer())
                {
                    var dialog = (Window)container.TryResolve <T> ();
                    dialog.Closed += (s, e) => onDialogClosed();
                    var result = dialog.ShowDialog();
                    return result;
                }

            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}

注意:MainActivity调用Player类并接收整数songIndex(重新表示ArrayList中的歌曲索引)

2 个答案:

答案 0 :(得分:2)

在playSong()方法中尝试此操作

if (mp.isPlaying()) {
    mp.stop();
    mp.relase();
    mp.prepare();
    mp.start();
}

答案 1 :(得分:0)

可能是您同时拥有多个媒体播放器实例吗?你应该检查一下。

您必须在活动的onStop()方法中释放媒体播放器,如下所示:

@Override
protected void onStop() {
super.onStop();  // Always call the superclass method first

mediaPlayer.release();
mediaPlayer = null;
}

来自官方文件:

As an example, consider the problems that could happen if you forgot to release the MediaPlayer when your activity is stopped, but create a new one when the activity starts again. 
As you may know, when the user changes the screen orientation (or changes the device configuration in another way), the system handles that by restarting the activity (by default), 
so you might quickly consume all of the system resources as the user rotates the device back and forth between portrait and landscape, 
because at each orientation change, you create a new MediaPlayer that you never release. 

同时拥有太多播放器实例,您将遇到OutOfMemory或太多打开文件等错误。

顺便说一下。你不应该直接使用构造函数,而是使用如下所述的create()方法实例化媒体播放器:

http://www.tutorialspoint.com/android/android_mediaplayer.htm