当前位置: 首页 > 知识库问答 >
问题:

Android-ListView中的音频播放器,具有音频播放的单个实例

缪嘉志
2023-03-14

我有listview,它包含一个带有播放按钮和搜索栏的音频文件列表。
当我单击listview的播放按钮时,我想播放一个音频文件。我成功地实现了这一点,但当我单击列表中的另一个播放按钮时,两个音频文件正在连续播放,它将继续所有单击播放按钮。我如何限制媒体播放器在一个位置播放,如果我点击另一个图标,它必须停止旧的媒体播放器,并开始播放新的。有人能说我怎么实现这个吗?。我有相同的按钮播放和暂停。

@SuppressLint("NewApi") public class ChatMessageAdapter1 extends BaseAdapter implements UpdatableAdapter, AnimationListener{

    public ChatMessageAdapter1(Activity activity) 
    {

//      MediaPlayer mp = new MediaPlayer();

    @Override
    public int getCount() {
        return messages.size() + 1;
    }

    @Override
    public Object getItem(int position) {
        if (position < messages.size())
            return messages.get(position);
        else
            return null;
    }

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

    @Override
    public int getViewTypeCount() {
        return 3;       
    }

    @Override
    public int getItemViewType(int position){
        if (position < messages.size())
        return TYPE_MESSAGE;
    else
        return hint == null ? TYPE_EMPTY : TYPE_HINT;   
    }

    //@SuppressLint("RtlHardcoded")
    @SuppressLint({ "RtlHardcoded", "NewApi" }) @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override
    public View getView(int position, View convertView, ViewGroup parent) 
    {
        final int type = getItemViewType(position); 
        final ViewHolder view;      
    //  final View view;
        if (convertView == null) 
        {           
            final int resource;
            if (type == TYPE_MESSAGE)
            {
                resource = R.layout.chat_viewer_message;
            }
            else if (type == TYPE_HINT)
                resource = R.layout.chat_viewer_info;
            else if (type == TYPE_EMPTY)
                resource = R.layout.chat_viewer_empty;
            else
                throw new IllegalStateException();
            convertView = activity.getLayoutInflater().inflate(resource, parent, false);            
            if (type == TYPE_MESSAGE)
            {
                ((TextView) convertView.findViewById(R.id.text)).setTextAppearance(activity, appearanceStyle);  
            }
            view= new ViewHolder();
            convertView.setTag(view);
        } 
        else
            view = (ViewHolder)convertView.getTag();
            //view = convertView;
        if (type == TYPE_EMPTY)
            return convertView;
        if (type == TYPE_HINT) {
            TextView textView = ((TextView) convertView.findViewById(R.id.info));
            textView.setText(hint);
            textView.setTextAppearance(activity, R.style.ChatInfo_Warning);
            return convertView;
        }
        final MessageItem messageItem = (MessageItem) getItem(position);
        final String name;
        final String account = messageItem.getChat().getAccount();
        final String user = messageItem.getChat().getUser();
        final String resource = messageItem.getResource();
        final boolean incoming = messageItem.isIncoming();
        final String messageText = messageItem.getText();
        if (isMUC) 
        {
            name = resource;
        } 
        else 
            name = "";

        convertView.setBackgroundColor(Color.TRANSPARENT);      
        view.textView = (TextView) convertView.findViewById(R.id.text);     
        final RelativeLayout layoutImage = (RelativeLayout) convertView.findViewById(R.id.layoutImage);
        RelativeLayout layoutAudio = (RelativeLayout) convertView.findViewById(R.id.layoutAudio);        
        view.imgView1 = (ImageView) convertView.findViewById(R.id.attachedImageNvideoShowAyushi);
        view.iconImageNvideo = (ImageView) convertView.findViewById(id.iconOnTopOfImageNVideo);
        view.imgAudioPlay = (ImageButton) convertView.findViewById(R.id.attachedAUDIOtattlePLAY);
        view.avatarView = (ImageView) convertView.findViewById(R.id.avatar);
        view.audioSeekBar = (SeekBar) convertView.findViewById(R.id.SeekBarAudioTattle);
        view.audioDuration =(TextView) convertView.findViewById(R.id.audioLengthTattle);
        view.dateTimeTattle = (TextView) convertView.findViewById(R.id.tattleDateTimeOnChatPage);
        view.statusTattle = (ImageView) convertView.findViewById(R.id.tattleStatusOnChatPage);
        view.datePast = (TextView) convertView.findViewById(R.id.pastDate);
//      view.tabhost = (TabHost) convertView.findViewById(R.id.tabhostAttach);






if(builder.toString().contains("ABCDEF_AUDIO"))
{
    layoutAudio.setVisibility(View.VISIBLE);    
    final MediaPlayer mp;

    final Handler durationHandler = new Handler();          
    view.audioSeekBar.setClickable(true);
    view.audioSeekBar.setVisibility(View.VISIBLE);
    view.imgView1.setVisibility(View.GONE);
    view.iconImageNvideo.setVisibility(View.GONE);
    view.textView.setVisibility(View.GONE);     
    String path = messageItem.getText();
    //System.out.println("AUDIO path : " + path);
    File PathDirectoryCHECK= new File(Environment.getExternalStorageDirectory().toString() + "/ABCDEF/ABCDEF_AUDIO");  
    final File PathofAudioCHECK = new File(PathDirectoryCHECK.getPath() + File.separator + path);
    //System.out.println("PathofAudioCHECK : " + PathofAudioCHECK);

    mp = new MediaPlayer();

    mp.setLooping(false);

              final Runnable runnableAudio = new Runnable() 
                 {
                        public void run() 
                        {                                                       
                            timeElapsed = mp.getCurrentPosition();
                            view.audioSeekBar.setProgress((int) timeElapsed);
                            finalTime = mp.getDuration();
                            double timeRemaining = finalTime - timeElapsed;
                            view.audioDuration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
                            durationHandler.postDelayed(this, 100);                                                 
                        }
                };    
    try {               
            if(PathofAudioCHECK.isFile())
            {
                final Uri audioUri=Uri.fromFile(PathofAudioCHECK);                      
                mp.setDataSource(activity,audioUri);    
                mp.setAudioStreamType(AudioManager.STREAM_MUSIC);                           
                mp.prepare();
                finalTime = mp.getDuration();
                view.audioSeekBar.setMax((int) finalTime);
                int duration = mp.getDuration();
                if(duration==-1)
                    view.audioDuration.setText("");
                else
                    view.audioDuration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((int) duration), TimeUnit.MILLISECONDS.toSeconds((int) duration)));

                view.audioSeekBar.setOnTouchListener(new OnTouchListener() 
                {   
                    @SuppressLint("ClickableViewAccessibility") @Override
                    public boolean onTouch(View v, MotionEvent event) 
                    {   
                        if(mp.isPlaying())
                        {
                            SeekBar sb = (SeekBar)v;
                            mp.seekTo(sb.getProgress());
                        }
                        return false;
                    }
                }); 

                view.imgAudioPlay.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View v)
                    {   
                        try
                        {
                            //System.out.println("test");s
                            //System.out.println(""+mp.toString()+"---"+mp.isPlaying());
                            if(mp.isPlaying() && mp!=null)
                            {
//                              mp.pause();
                                mp.stop();
                                mp.reset();
                                mp.release();

                                if(incoming) {
                                    view.imgAudioPlay.setImageResource(R.drawable.audio_play_incoming_tattle);
                                }
                                else {
                                    view.imgAudioPlay.setImageResource(R.drawable.audio_play_outgoing_tattle);
                                }                               
                            }
                            else if(!mp.isPlaying())
                            {
                                if(mp!=null)
                                {
                                    /*try {
                                        mp.setDataSource(activity,audioUri);    
                                        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);   
                                        mp.prepare();                                       
                                        } 
                                    catch (IllegalStateException e) {
                                        e.printStackTrace();
                                    } 
                                    catch (IOException e) {
                                        e.printStackTrace();
                                    }*/
                                    mp.start(); 
                                    if(incoming)
                                    {
                                        view.imgAudioPlay.setImageResource(R.drawable.audio_pause_incoming_tattle);                                         
                                    }
                                    else 
                                    {
                                        view.imgAudioPlay.setImageResource(R.drawable.audio_pause__outgoing_tattle);
                                    }
                                    timeElapsed = mp.getCurrentPosition();
                                    view.audioSeekBar.setProgress((int) timeElapsed);                                            
                                     durationHandler.postDelayed(runnableAudio, 100);
                                     mp.setOnCompletionListener(new OnCompletionListener() {                                                
                                        @Override
                                        public void onCompletion(MediaPlayer mp) {
                                            view.audioSeekBar.setProgress(0);
                                            mp.seekTo(0);
                                            mp.reset();
                                            mp.stop();
                                            mp.release();
                                            durationHandler.removeCallbacks(runnableAudio);
                                        }
                                    });
                                     mp.setOnSeekCompleteListener(new OnSeekCompleteListener()
                                        {               
                                            public void onSeekComplete(MediaPlayer mp) {
                                                view.audioSeekBar.setProgress(0);
                                                mp.reset();
                                                mp.stop();                  
                                                //mp.release();                 
                                                durationHandler.removeCallbacks(runnableAudio);
                                            }
                                        });
                        }}
                    }
                    catch (IllegalStateException e) {
                        e.printStackTrace();
                    } 
                    }});                            
            }
            else if(!PathofAudioCHECK.isFile() || PathofAudioCHECK==null)
                {
                        if(incoming)
                        {
                            if(counterDOWNLOADfromSERVER!=1)
                            {
                                counterDOWNLOADfromSERVER=1;
                                String[] parts = path.split("\\."); // String array, each element is text between dots
                                String beforeFirstDot = parts[0];
                                String pathSubStr=beforeFirstDot.substring(13);             
                            //  System.out.println("BUILDER name ID : " + pathSubStr);                  
                                String url = configurationsFileTransfer.FILE_URL_TRANSFER + pathSubStr;
                                new HttpAsyncTaskforAudio().execute(url);
                                //System.out.println("AUDIo received  : " + get_newPathofAUDIOreceived());
                                try
                                {                               
                                if(get_newPathofAUDIOreceived().exists() || get_newPathofAUDIOreceived().isFile() || get_newPathofAUDIOreceived()!=null)
                                {                
                                    final Uri audioUri=Uri.fromFile(get_newPathofAUDIOreceived());
                                    mp.setDataSource(activity,audioUri);    
                                    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                                    mp.prepare();
                                    finalTime = mp.getDuration();
                                    view.audioSeekBar.setMax((int) finalTime);
                                    view.audioSeekBar.setMax(mp.getDuration());
                                    int duration = mp.getDuration();
                                    if(duration==-1)
                                        view.audioDuration.setText("");
                                    else
                                        view.audioDuration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((int) duration), TimeUnit.MILLISECONDS.toSeconds((int) duration)));

                                    view.audioSeekBar.setOnTouchListener(new OnTouchListener() 
                                    {   
                                        @SuppressLint("ClickableViewAccessibility") @Override
                                        public boolean onTouch(View v, MotionEvent event) 
                                        {   
                                            if(mp.isPlaying())
                                            {
                                                SeekBar audioSeekBar = (SeekBar)v;
                                                mp.seekTo(audioSeekBar.getProgress());
                                            }
                                            return false;
                                        }
                                    });     
                                    view.imgAudioPlay.setOnClickListener(new View.OnClickListener()
                                    {
                                        public void onClick(View v)
                                        {
                                            if(mp.isPlaying() && mp!=null)
                                            {
                                                mp.pause();
                                                if(incoming)
                                                {
                                                    view.imgAudioPlay.setImageResource(R.drawable.audio_pause_incoming_tattle);                                         
                                                }
                                                else 
                                                {
                                                    view.imgAudioPlay.setImageResource(R.drawable.audio_pause__outgoing_tattle);
                                                }                                               
                                            }
                                            else if(!mp.isPlaying())
                                            {
                                                if(mp!=null)
                                                {
                                                    try {
                                                        mp.setDataSource(activity,audioUri);    
                                                        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);   
                                                        mp.prepare();

                                                    } catch (IllegalStateException e) {
                                                        e.printStackTrace();
                                                    } catch (IOException e) {
                                                        e.printStackTrace();
                                                    }
                                                    mp.start(); 
                                                    if(incoming)
                                                    {
                                                        view.imgAudioPlay.setImageResource(R.drawable.audio_play_incoming_tattle);
                                                    }
                                                    else 
                                                    {
                                                        view.imgAudioPlay.setImageResource(R.drawable.audio_play_outgoing_tattle);
                                                    }
                                                    timeElapsed = mp.getCurrentPosition();
                                                    view.audioSeekBar.setProgress((int) timeElapsed);                                            
                                                     durationHandler.postDelayed(runnableAudio, 100);
                                                     mp.setOnCompletionListener(new OnCompletionListener() {                                                
                                                        @Override
                                                        public void onCompletion(MediaPlayer mp) {
                                                            mp.seekTo(0);
                                                            mp.reset();
                                                            mp.stop();
                                                                //mp.release();
                                                                durationHandler.removeCallbacks(runnableAudio);
                                                        }
                                                    });                                         
                                                }
                                            }
                                        }
                                        });                                         
                                }
                                        else
                                        {
                                            System.out.println("Audio Deleted! 1 ");
                                        }
                                    }
                                        catch(NullPointerException e)
                                        {
                                            System.out.println("null error : " + e.getMessage());
                                        }
                                    }
                                    else 
                                    {                                   }
                                }
                                else 
                                {           System.out.println("Audio Deleted! 2");
                                }
                            }                   
                }
            catch(NullPointerException e)
            {
                        //String pathA = messageItem.getText();
                        //System.out.println("AUDIO path A : " + pathA);
            } catch (IllegalArgumentException e1) {
                e1.printStackTrace();
            } catch (SecurityException e1) {
                e1.printStackTrace();
            } catch (IllegalStateException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
//          mp.setOnSeekCompleteListener(new OnSeekCompleteListener()
//          {               
//              public void onSeekComplete(MediaPlayer mp) {
//                  audioSeekBar.setProgress(0);
//                  mp.reset();
//                  mp.stop();                  
//                  mp.release();                   
//                  mp=null;
//                  durationHandler.removeCallbacks(runnableAudio);
//              }
//          });     
            if(activity.isChangingConfigurations())
            {
                mp.stop();
                mp.reset();
                //mp.release();
            }
            if (activity.isFinishing()){                
                mp.stop();
                mp.reset();
                //mp.release();
            }   
        }       

        return convertView;
    }

    public String getAccount() {
        return account;
    }

    public String getUser() {
        return user;
    }

    public static String GET(String url){
        InputStream inputStream = null;
        String result = "";
        try {

            HttpClient httpclient = new DefaultHttpClient(); 
            HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
             inputStream = httpResponse.getEntity().getContent(); 
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!"; 
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        } 
        return result;
    }




         private File newPathDirectoryforAudio;
            private static File newPathofAUDIOreceived;

         private String fid_response_audio;
            private class HttpAsyncTaskforAudio extends AsyncTask<String, Void, String> {
                @Override
                protected String doInBackground(String... urls) 
                {
                    return GET(urls[0]);
                }
                @Override
                protected void onPostExecute(String result)
                {
//                  System.out.println("RESULT AUDIO : " + result);
                    JSONObject json;            
                    try {
                        json = new JSONObject(result);          
                        fid_response=json.getString("fid");
                        String fileNAME_response=json.getString("name");
                                String audioUrl = configurationsFileTransfer.FILE_URL_MEDIA + fileNAME_response;
//                              System.out.println("audioURL : " + audioUrl);                           
                                set_fid_response_audio(fid_response_audio);
                                 new DownloadFileAUDIOfromURL().execute(audioUrl);              
                    } catch (JSONException e) 
                    {
                        e.printStackTrace();
                    }
               }
            }           
            class DownloadFileAUDIOfromURL extends AsyncTask<String, String, String> 
            {       
                @Override
                protected String doInBackground(String... f_url) {
                    int count;
                    try
                    {
                        URL url = new URL(f_url[0]);
                        URLConnection conection = url.openConnection();
                        conection.connect();
                        int lenghtOfFile = conection.getContentLength();
                        InputStream input = new BufferedInputStream(url.openStream(), 8192);    
                        newPathDirectoryforAudio = new File(Environment
                                .getExternalStorageDirectory().toString() + "/TATTLE/TATTLE_AUDIO");
                        if(!newPathDirectoryforAudio.exists())
                        {
                            newPathDirectoryforAudio.mkdirs();
                        }            

                        newPathofAUDIOreceived = new File(newPathDirectoryforAudio.getPath() + File.separator + "TATTLE_AUDIO_"+ get_fid_response() + ".mp3");
                        set_newPathofAUDIOreceived(newPathofAUDIOreceived); 
                        OutputStream output = new FileOutputStream(newPathofAUDIOreceived);
                        byte data[] = new byte[1024];
                        long total = 0;
                        while ((count = input.read(data)) != -1) 
                        {
                            total += count;                 
                            publishProgress(""+(int)((total*100)/lenghtOfFile));   
                            output.write(data, 0, count);
                        }
                        output.flush();
                        output.close();
                        input.close();              
                    } 
                    catch (Exception e)
                    {
                        Log.e("Error: ", e.getMessage());
                    }           
                    return null;
                 }      

                @Override
                protected void onPostExecute(String file_url) 
                {
//                  System.out.println("Set incoming audios from this path : " + newPathofAUDIOreceived.toString());                
                    set_newPathofAUDIOreceived(newPathofAUDIOreceived); 
                    notifyDataSetChanged();             
                }               
            }
             private void set_fid_response_audio(String fid_response_audio)
               {
                   this.fid_response_audio= fid_response_audio;
               }
//           private String get_fid_response_audio()
//             {
//                 return fid_response_audio;
//             }
             private static void set_newPathofAUDIOreceived(File newPathofAUDIOreceived)
               {
                   ChatMessageAdapter.newPathofAUDIOreceived= newPathofAUDIOreceived;
               }
             private static File get_newPathofAUDIOreceived()
               {
                   return newPathofAUDIOreceived;
               }

共有1个答案

袁增
2023-03-14
 if(builder.toString().contains("ABCDEF_AUDIO"))
    {
        layoutAudio.setVisibility(View.VISIBLE);    
        final MediaPlayer mp;
        final Handler durationHandler = new Handler();          
        view.audioSeekBar.setClickable(true);
        view.audioSeekBar.setVisibility(View.VISIBLE);
        view.imgView1.setVisibility(View.GONE);
        view.iconImageNvideo.setVisibility(View.GONE);
        view.textView.setVisibility(View.GONE);     
        String path = messageItem.getText();
        //System.out.println("AUDIO path : " + path);
        File PathDirectoryCHECK= new File(Environment.getExternalStorageDirectory().toString() + "/ABCDEF/ABCDEF_AUDIO");  
        final File PathofAudioCHECK = new File(PathDirectoryCHECK.getPath() + File.separator + path);
        //System.out.println("PathofAudioCHECK : " + PathofAudioCHECK); 
        mp = new MediaPlayer();    
        mp.setLooping(false);
                  final Runnable runnableAudio = new Runnable() 
                     {
                            public void run() 
                            {                                                       
                                timeElapsed = mp.getCurrentPosition();
                                view.audioSeekBar.setProgress((int) timeElapsed);
                                finalTime = mp.getDuration();
                                double timeRemaining = finalTime - timeElapsed;
                                view.audioDuration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
                                durationHandler.postDelayed(this, 100);                                                 
                            }
                    };    
        try {               
                if(PathofAudioCHECK.isFile())
                {
                    final Uri audioUri=Uri.fromFile(PathofAudioCHECK);                      
                    mp.setDataSource(activity,audioUri);    
                    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);                           
                    mp.prepare();
                    finalTime = mp.getDuration();
                    view.audioSeekBar.setMax((int) finalTime);
                    int duration = mp.getDuration();
                    if(duration==-1)
                        view.audioDuration.setText("");
                    else
                        view.audioDuration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((int) duration), TimeUnit.MILLISECONDS.toSeconds((int) duration)));

                    view.audioSeekBar.setOnTouchListener(new OnTouchListener() 
                    {   
                        @SuppressLint("ClickableViewAccessibility") @Override
                        public boolean onTouch(View v, MotionEvent event) 
                        {   
                            if(mp.isPlaying())
                            {
                                SeekBar sb = (SeekBar)v;
                                mp.seekTo(sb.getProgress());
                            }
                            return false;
                        }
                    });                 
                    view.imgAudioPlay.setOnClickListener(new View.OnClickListener()
                    {
                        public void onClick(View v)
                        {   
                            try
                            {
                                if(isPlaying && !mp.isPlaying() && mp!=null)
                                {
                                    mpG.pause();                                
                                }
                                if(mp!=null && mp.isPlaying())
                                {
                                    mp.pause();
                                    isPlaying = false;                      

                                }
                                else if(!mp.isPlaying())
                                {
                                    if(mp!=null)
                                    {

                                        mpG = mp;
                                        isPlaying = true;
                                        vhG = view;
                                        mp.start(); 

                                        timeElapsed = mp.getCurrentPosition();
                                        view.audioSeekBar.setProgress((int) timeElapsed);                                            
                                         durationHandler.postDelayed(runnableAudio, 100);

                                         mp.setOnCompletionListener(new OnCompletionListener() {                                                
                                            @Override
                                            public void onCompletion(MediaPlayer mp) {                                          
                                                view.audioSeekBar.setProgress(0);
                                                mp.seekTo(0);
                                                mp.reset();
                                                mp.stop();                                          
                                                isPlaying = false;
                                                mp.release();
                                                durationHandler.removeCallbacks(runnableAudio);

                                                notifyDataSetChanged();
                                            }
                                        });
                                         mp.setOnSeekCompleteListener(new OnSeekCompleteListener()
                                            {               
                                                public void onSeekComplete(MediaPlayer mp) {                                                
    //                                              System.out.println("Audio : 6");
                                                    view.audioSeekBar.setProgress(0);
                                                    mp.reset();
                                                    mp.stop();  
                                                    isPlaying = false;
                                                    mp.release();       

                                                    durationHandler.removeCallbacks(runnableAudio);
                                                    notifyDataSetChanged();
                                                }
                                            });
                            }
                                    }

                        }
                        catch (IllegalStateException e) {
                            e.printStackTrace();
                        } 
                        }});                            
                }
                else if(!PathofAudioCHECK.isFile() || PathofAudioCHECK==null)
                {
                            if(incoming)
                            {
                                if(counterDOWNLOADfromSERVER!=1)
                                {
                                    counterDOWNLOADfromSERVER=1;
                                    String[] parts = path.split("\\."); // String array, each element is text between dots
                                    String beforeFirstDot = parts[0];
                                    String pathSubStr=beforeFirstDot.substring(13);             
                                //  System.out.println("BUILDER name ID : " + pathSubStr);                  
                                    String url = configurationsFileTransfer.FILE_URL_TRANSFER + pathSubStr;
                                    new HttpAsyncTaskforAudio().execute(url);
                                    //System.out.println("AUDIo received  : " + get_newPathofAUDIOreceived());
                                    try
                                    {                               
                                    if(get_newPathofAUDIOreceived().exists() || get_newPathofAUDIOreceived().isFile() || get_newPathofAUDIOreceived()!=null)
                                    {                
                                        final Uri audioUri=Uri.fromFile(get_newPathofAUDIOreceived());
                                        mp.setDataSource(activity,audioUri);    
                                        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                                        mp.prepare();
                                        finalTime = mp.getDuration();
                                        view.audioSeekBar.setMax((int) finalTime);
                                        view.audioSeekBar.setMax(mp.getDuration());
                                        int duration = mp.getDuration();
                                        if(duration==-1)
                                            view.audioDuration.setText("");
                                        else
                                            view.audioDuration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((int) duration), TimeUnit.MILLISECONDS.toSeconds((int) duration)));

                                        view.audioSeekBar.setOnTouchListener(new OnTouchListener() 
                                        {   
                                            @SuppressLint("ClickableViewAccessibility") @Override
                                            public boolean onTouch(View v, MotionEvent event) 
                                            {   
                                                if(mp.isPlaying())
                                                {
                                                    SeekBar audioSeekBar = (SeekBar)v;
                                                    mp.seekTo(audioSeekBar.getProgress());
                                                }
                                                return false;
                                            }
                                        });     
                                        view.imgAudioPlay.setOnClickListener(new View.OnClickListener()
                                        {
                                            public void onClick(View v)
                                            {
                                                if(isPlaying && !mp.isPlaying() && mp!=null){
                                                    mpG.pause();

                                                }
                                                if(mp.isPlaying() && mp!=null)
                                                {
                                                    mp.pause();
                                                    isPlaying = false;

                                                }
                                                else if(!mp.isPlaying())
                                                {
                                                    if(mp!=null)
                                                    {
                                                        try {
                                                            mp.setDataSource(activity,audioUri);    
                                                            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);   
                                                            mp.prepare();

                                                        } catch (IllegalStateException e) {
                                                            e.printStackTrace();
                                                        } catch (IOException e) {
                                                            e.printStackTrace();
                                                        }
                                                        mpG = mp;
                                                        isPlaying = true;
                                                        vhG = view;
                                                        mp.start(); 

                                                        timeElapsed = mp.getCurrentPosition();
                                                        view.audioSeekBar.setProgress((int) timeElapsed);                                            
                                                         durationHandler.postDelayed(runnableAudio, 100);
                                                         mp.setOnCompletionListener(new OnCompletionListener() {                                                
                                                            @Override
                                                            public void onCompletion(MediaPlayer mp) {
                                                                mp.seekTo(0);
                                                                mp.reset();
                                                                mp.stop();
                                                                isPlaying = false;

                                                                    durationHandler.removeCallbacks(runnableAudio);


                                                            }
                                                        });                                         
                                                    }
                                                }
                                            }
                                            });                                         
                                    }
                                            else
                                            {
                                                System.out.println("Audio Deleted! 1 ");
                                            }
                                        }
                                            catch(NullPointerException e)
                                            {
                                                System.out.println("null error : " + e.getMessage());
                                            }
                                        }
                                        else 
                                        {                                   }
                                    }
                                    else 
                                    {           System.out.println("Audio Deleted! 2");
                                    }
                                }                   
                    }
                catch(NullPointerException e)
                {
                } catch (IllegalArgumentException e1) {
                    e1.printStackTrace();
                } catch (SecurityException e1) {
                    e1.printStackTrace();
                } catch (IllegalStateException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                if(activity.isChangingConfigurations())
                {
                    mp.stop();
                    mp.reset();
                }
                if (activity.isFinishing()){                
                    mp.stop();
                    mp.reset();
                }   
            }
 类似资料:
  • 我正在开发一个包含一些音频播放器的RecyclerView的应用程序。应用程序将下载。3gp文件(如果尚未下载)。 当我单击playAudio按钮时,音频未被播放。 这是我的适配器代码: 我怎样才能解决这个问题?

  • 音频的加载方式请参考:声音资源 使用 AudioSource 组件播放 在 层级管理器 上创建一个空节点 选中空节点,在 属性检查器 最下方点击 添加组件 -> 其他组件 -> AudioSource 来添加 AudioSource 组件 将 资源管理器 中所需的音频资源拖拽到 AudioSource 组件的 Clip 中,如下所示: 然后根据需要对 AudioSource 组件的其他参数项进行设

  • 大家好,我正在尝试使用两个独立的媒体播放器实例播放音频和视频文件。当我从一开始播放它时,它工作得很好。但当我寻找时,我可以看到音频和视频的延迟 这是我寻找音频和视频的代码 //sikAudio(msec); if(media播放器!=null) { // 没有直播流,如果(medialayer.get持续时间() }

  • 一款带有圆形进度条的在线音频播放器。 [Code4App.com]

  • 本文向大家介绍web-audio 播放音频,包括了web-audio 播放音频的使用技巧和注意事项,需要的朋友参考一下 示例 要使用Web Audio API播放音频,我们需要获取音频数据的ArrayBuffer并将其传递给BufferSource进行播放。 要获得播放声音的音频缓冲区,您需要使用如下AudioContext.decodeAudioData方法: 最终承诺解决后,系统会以的形式为您

  • 音频播放组件,代替原生的 audio 标签 标题 内容 类型 通用 支持布局 N/S 所需脚本 https://c.mipcdn.com/static/v2/mip-audio/mip-audio.js mip-audio 用法和原生标签的用法基本相同,有所不同的是在 MIP 环境下,初始化的时间是由 MIP Runtime 决定,只有当标签在浏览器视窗内才会初始化,也就是所谓的懒加载。 mip-