6

我需要在我的应用程序中从远程服务器播放音频文件。当我使用 localhost 服务器(使用 WAMP)进行测试时,我可以玩。当服务器提供的相同文件不起作用时..文件没有扩展名,内容是 MP3

String fileUrl = "http://192.168.1.131/myproject/songs/xyz";
String url = "http://myserver/songs/xyz"; //(myserver -> A remote server)
mVideoView.setVideoURI(Uri.parse(fileUrl));
mVideoView.requestFocus();

我还需要更好地控制玩家。
请帮忙...

4

5 回答 5

14
public void onRadioClick(View v) {

    if (!isPLAYING) {
        isPLAYING = true;
        MediaPlayer mp = new MediaPlayer();
        try {
            mp.setDataSource(getString(R.string.audio_stream));
            mp.prepare();
            mp.start();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    } else {
        isPLAYING = false;
        stopPlaying();
    }
}

private void stopPlaying() {
    mp.release();
    mp = null;
}
于 2011-05-12T06:58:25.773 回答
9

上面提供的答案提供了同步获取和播放,这意味着当前正在执行的线程将被阻塞,直到 prepare() 完成。

prepareAsync() 可用于异步“准备”流。您还需要处理 onPrepared() 事件才能开始播放。

mediaPlayer.setDataSource(URL here);
mediaPlayer.prepareAsync();

添加 OnPrepared 事件处理程序:

mPlayer.setOnPreparedListener(new OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
        mPlayer.start();
    }
});

尽管如此,显然没有办法配置流缓冲区大小。令人沮丧...

于 2012-12-27T11:23:37.750 回答
5
> import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.widget.SeekBar;

import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.InterstitialAd;

/**
 * @author Rashid Ali
 * @Date Sep 18, 2014
 * @Email <rashid.android.developer@gmail.com>
 * 
 */

public class AudioPlayerActivity extends Activity implements OnClickListener,
        OnTouchListener, OnCompletionListener, OnBufferingUpdateListener,
        AdListener {

    private ProgressDialog progressBar;

    private static final String AD_UNIT_ID_GOES_HERE = "ca-app-pub-5453344383403527/5064575693";
    private InterstitialAd interstitialAd;

    private ImageButton buttonPlayPause;
    private SeekBar seekBarProgress;

    private MediaPlayer mediaPlayer;
    private int mediaFileLengthInMilliseconds; // this value contains the song
                                                // duration in milliseconds.
                                                // Look at getDuration() method
                                                // in MediaPlayer class

    private final Handler handler = new Handler();

    String audioName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_player);

        interstitialAd = new InterstitialAd(this, AD_UNIT_ID_GOES_HERE);
        interstitialAd.setAdListener(this);
        AdRequest adRequest = new AdRequest();
        adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
        interstitialAd.loadAd(adRequest);

        initilizeUI();

        Intent intent = getIntent();
        audioName = intent.getStringExtra("audioName");

    }

    /** This method is used to Initialize UI Components. */
    private void initilizeUI() {
        buttonPlayPause = (ImageButton) findViewById(R.id.ButtonTestPlayPause);
        buttonPlayPause.setOnClickListener(this);
        seekBarProgress = (SeekBar) findViewById(R.id.SeekBarTestPlay);
        seekBarProgress.setMax(99);
        seekBarProgress.setOnTouchListener(this);

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnBufferingUpdateListener(this);
        mediaPlayer.setOnCompletionListener(this);
    }

    /**
     * Method which updates the SeekBar primary progress by current song playing
     * position
     */
    private void primarySeekBarProgressUpdater() {
        seekBarProgress.setProgress((int) (((float) mediaPlayer
                .getCurrentPosition() / mediaFileLengthInMilliseconds) * 100)); // This
                                                                                // math
                                                                                // construction
                                                                                // give
                                                                                // a
                                                                                // percentage
                                                                                // of
                                                                                // "was playing"/"song length"
        if (mediaPlayer.isPlaying()) {
            Runnable notification = new Runnable() {
                public void run() {
                    primarySeekBarProgressUpdater();
                }
            };
            handler.postDelayed(notification, 1000);
        }
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        /**
         * Method which updates the SeekBar secondary progress by current song
         * loading from URL position
         */
        seekBarProgress.setSecondaryProgress(percent);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        /**
         * MediaPlayer onCompletion event handler. Method which calls then song
         * playing is complete
         */
        // buttonPlayPause.setImageResource(R.drawable.button_play);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.SeekBarTestPlay) {
            /**
             * Seekbar onTouch event handler. Method which seeks MediaPlayer to
             * seekBar primary progress position
             */
            if (mediaPlayer.isPlaying()) {
                SeekBar sb = (SeekBar) v;
                int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100)
                        * sb.getProgress();
                mediaPlayer.seekTo(playPositionInMillisecconds);
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ButtonTestPlayPause) {
            /**
             * ImageButton onClick event handler. Method which start/pause
             * mediaplayer playing
             */
            try {
                mediaPlayer.setDataSource(audioName); // setup
                                                        // song
                                                        // from
                                                        // http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3
                                                        // URL
                                                        // to
                                                        // mediaplayer
                                                        // data
                                                        // source
                mediaPlayer.prepare(); // you must call this method after setup
                                        // the datasource in setDataSource
                                        // method. After calling prepare() the
                                        // instance of MediaPlayer starts load
                                        // data from URL to internal buffer.
            } catch (Exception e) {
                e.printStackTrace();
            }

            mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets
                                                                        // the
                                                                        // song
                                                                        // length
                                                                        // in
                                                                        // milliseconds
                                                                        // from
                                                                        // URL

            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                buttonPlayPause.setImageResource(R.drawable.pause_button);

            } else {
                mediaPlayer.pause();
                buttonPlayPause.setImageResource(R.drawable.play_button);
            }
            primarySeekBarProgressUpdater();
        }
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
        mediaPlayer.stop();
        this.finish();
    }

    @Override
    public void onDismissScreen(Ad arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLeaveApplication(Ad arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPresentScreen(Ad arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onReceiveAd(Ad ad) {
        // TODO Auto-generated method stub
        if (ad == interstitialAd) {
            interstitialAd.show();
        }
    }

}

<RelativeLayout
    android:id="@+id/layout_header"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@drawable/header" >
</RelativeLayout>

<RelativeLayout
    android:id="@+id/ad_layout"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_below="@+id/layout_header" >

    <com.google.ads.AdView
        android:id="@+id/googleads"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-5453344383403527/9634376094"
        ads:loadAdOnCreate="true" >
    </com.google.ads.AdView>
</RelativeLayout>

<RelativeLayout
    android:id="@+id/ad_layout"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true" >

    <com.google.ads.AdView
        android:id="@+id/googleads"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-5453344383403527/2111109291"
        ads:loadAdOnCreate="true" >
    </com.google.ads.AdView>
</RelativeLayout>

    <RelativeLayout
        android:id="@+id/functional_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true" >

        <ImageButton
            android:id="@+id/ButtonTestPlayPause"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginLeft="10dp"
            android:src="@drawable/play_button" />

        <SeekBar
            android:id="@+id/SeekBarTestPlay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_toRightOf="@+id/ButtonTestPlayPause" />
    </RelativeLayout>

于 2015-04-03T09:38:14.683 回答
3

如果您正在编写 Java 程序来播放媒体文件,那么第一个调用端口是 MediaPlayer 类。使用 MediaPlayer 的流机制播放文件的典型代码是

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        Uri uri = Uri.parse("http://192.168.1.9/music/test.ogg");
        MediaPlayer player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setDataSource(this, uri);
        player.prepare();
        player.start();
    } catch(Exception e) {
        System.out.println(e.toString());
    }
}

唤醒锁定权限 - 如果您的播放器应用程序需要防止屏幕变暗或处理器处于休眠状态,或者使用 MediaPlayer.setScreenOnWhilePlaying() 或 MediaPlayer.setWakeMode() 方法,则必须请求此权限。

<uses-permission android:name="android.permission.WAKE_LOCK" />
于 2017-05-04T22:25:18.577 回答
0

我通过使用以下 Kotlin 扩展来进行 url 流式传输MediaPlayer

fun ImageButton.playFromUrl(
    url: String,
    onStart: MediaPlayer.() -> Unit
) {
    val audioAttributes = AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_MEDIA)
        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
        .build()

    MediaPlayer().apply {
        setAudioAttributes(audioAttributes)
        setDataSource(url)

        setOnPreparedListener {
            isEnabled = false
            start()
            setImageDrawable(context.getDrawableResource(R.drawable.ic_baseline_stop_24))
        }

        setOnCompletionListener {
            setImageDrawable(context.getDrawableResource(R.drawable.ic_baseline_volume_up_24))
            release()
            isEnabled = true
        }
    }.onStart()
}

上述函数的用法如下

btnVoice.setOnSingleClickListener {
    if(it.isInternetAvailable()){
        (it as ImageButton).playFromUrl(phonetic.audio){
            prepareAsync()
        }
    }
}
于 2021-06-17T04:53:30.880 回答