MediaPlayer.setDataSource() 和 prepare() 不起作用 - android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3533837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:39:11  来源:igfitidea点击:

MediaPlayer.setDataSource() and prepare() not working - android

androidmedia-playerprepare

提问by Kyle

I'm having a crack at using the MediaPlayer object and not having much success. If I add a sound asset to my raw folder and call it using the int value within R, it works fine. But I want to be able to pull things off of url.

我在使用 MediaPlayer 对象方面遇到了困难,但没有取得太大的成功。如果我将声音资产添加到我的原始文件夹并使用 R 中的 int 值调用它,它工作正常。但我希望能够从 url 中提取东西。

According to all of the documentation I've read setDataSource() should accept a string param with a url to a file.

根据我读过的所有文档, setDataSource() 应该接受一个带有文件 url 的字符串参数。

I keep getting an IO exception on the prepare() statement. I've even tried copying the file locally and still no dice.

我一直在 prepare() 语句上收到 IO 异常。我什至尝试在本地复制文件,但仍然没有骰子。

Anyone have any ideas?

谁有想法?

MediaPlayer mp = new MediaPlayer();
try {
        mp.setDataSource("http://www.urltofile.com/file.mp3");
        mp.prepare();
        mp.start();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

回答by Konstantin Burov

Try MediaPlayer.create(), you also may want to start only after player is actually ready, for example:

试试 MediaPlayer.create(),你也可能想在播放器真正准备好后才开始,例如:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MediaPlayer player = MediaPlayer.create(this, Uri.parse("http://www.urltofile.com/file.mp3"));
    player.setOnPreparedListener(new OnPreparedListener() { 
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    });
}

回答by Ihor DIM

For streams, you should call prepareAsync(), which returns immediately, rather than blocking until enough data has been buffered.

对于流,您应该调用prepareAsync(),它会立即返回,而不是阻塞直到缓冲了足够的数据。