【问题标题】:Browse for a sound file in android在android中浏览声音文件
【发布时间】:2017-02-08 19:14:19
【问题描述】:

我目前正在编写一个模拟来电的应用程序。 我想为用户提供选项,指定一个声音文件,当他接受呼叫时将开始播放。 我想让用户轻松浏览他的电话目录并指定一个文件。 我想要一些关于如何做的建议。(不要求解决方案只是一些提示,因为我对 android 编程相当陌生。) 在此先感谢:D

【问题讨论】:

    标签: android android-studio audio


    【解决方案1】:

    当你想选择音频时,你可以在你的项目中添加以下代码。

    public class SoundActivity extends Activity {
    
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
        //for example you have a button that open SoundBrowser when trigger
        OpenSoundFileButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setType("audio/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(intent,1);
                }
            });
    
         }
    
    // override onActivityResult in the same Activity, as below
    
            @Override 
        protected void onActivityResult(int requestCode,int resultCode,Intent data){
    
          if(requestCode == 1){
    
            if(resultCode == RESULT_OK){
    
                //the selected audio.
                Uri myUri = data.getData(); 
    
                //and by taken uri you can start your Media
                MediaPlayer mPlayer = new MediaPlayer();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.setDataSource(getApplicationContext(), myUri);
                mPlayer.prepare();
                mPlayer.start();
            }
          }
          super.onActivityResult(requestCode, resultCode, data);
        }
    }
    

    【讨论】:

    • 我确信这是一个很好的答案,但正如我所说,我对 android 编程相当陌生,如果您能多解释一下您的代码,我将不胜感激。我想要做的是显示类似文件浏览器的内容,然后将带有所选文件的 uri 返回到我的 Activity,该 Activity 将使用 MediaPlayer 播放它。
    • @Dimitris 答案已更新,如有困难请告知。
    • 哦,我想我现在明白了。您的意思是,我必须创建浏览器活动并将其传递给创建的 Intent(onClick 下的那个),然后我将使用覆盖的 onActivityResult 方法获得结果,对吧?
    • @Dimitris 不不不!通过使用:Intent intent = new Intent(); intent.setType("audio/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent,1); 您要求 android 打开您仅指定“音频”的文件浏览器,您可以选择它们。选择音频后,它会返回您的应用程序,您可以在其中使用所选音频并播放该音频。首先请尝试代码,您会看到奇迹发生。
    • 有效!非常感谢您对迟到的反馈感到抱歉,但我这个月没有太多时间继续我的应用程序的工作,我今天又开始工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多