如何使用MusicPlayService播放音乐

时间:2021-09-11 19:00:46

I'm a student and just started learning java and android(currently using android studio). I have been following a tutorial with video streaming and music streaming. but I'm currently following with music streaming.

我是一名学生,刚开始学习java和android(目前正在使用android studio)。我一直在关注视频流和音乐流媒体的教程。但我目前正在关注音乐流媒体。

Code is fine but the problem is It won't stream the music. Also there's no error showing that I missed something or anything in the program. It is running on the emulator but it just wont play the music.

代码很好,但问题是它不会流式传输音乐。此外,没有错误表明我错过了程序中的某些内容或任何内容。它在模拟器上运行,但它不会播放音乐。

Below is my code for the MainActivity.java:

下面是我的MainActivity.java代码:

package com.name.package.yb;

import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Toast;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;


public class MainActivity extends AppCompatActivity {

    private Button btnPlayStop;
    private boolean boolMusicPlaying = false;
    Intent myService;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try{
            myService = new Intent(MainActivity.this, MusicPlayService.class);
            initViews();
            setListeners();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), e.getClass().getName() + " " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void initViews() {
        btnPlayStop = (Button) findViewById(R.id.myButton);
        btnPlayStop.setText("Stream Music");
    }

    private void setListeners() {
        btnPlayStop.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                btnPlayStopClick();
            }
        });
    }

    private void btnPlayStopClick() {
        if (!boolMusicPlaying) {
            btnPlayStop.setText("Pause Streaming");
            playAudio();
            boolMusicPlaying = true;
        } else {
            if(boolMusicPlaying){
                btnPlayStop.setText("Play Stream");
                stopPlayService();
                boolMusicPlaying = false;
            }
        }
    }

    private void stopPlayService() {
        try {
            stopService(myService);
        } catch (Exception e){
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),
                    e.getClass().getName() + " " + e.getMessage(),
                    Toast.LENGTH_LONG).show();
        }
        boolMusicPlaying = false;
    }

    private void playAudio() {
        try {
            startService(myService);
        } catch (Exception e) {
            e.printStackTrace();
           Toast.makeText(getApplicationContext(),e.getClass().getName() + " " + e.getMessage(),Toast.LENGTH_LONG).show();
        }
    }
}

And My Service named MusicPlayService.java (I want to play the music in background like the music player on phone):

我的服务名为MusicPlayService.java(我想在背景中播放音乐,就像手机上的音乐播放器一样):

package com.name.package.yb;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import java.io.IOException;


public class MusicPlayService extends Service  {

    private MediaPlayer mediaPlayer = new MediaPlayer();
    private static final String AUDIO_STRING = "http://musicsite.streammusic.com/file";

    @Override
    public void onCreate(){
        super.onCreate();
        //mediaPlayer.setOnCompletionListener(this);
        //mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setVolume(100,100);
        //mediaPlayer.reset();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        if (!mediaPlayer.isPlaying()) {
            try {
                mediaPlayer.setDataSource(AUDIO_STRING);
                // Prepare mediaplayer
                mediaPlayer.prepareAsync();
                mediaPlayer.start();

            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
            }
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
        }
    }

    public IBinder onBind(Intent arg0) {
        return null;
    }

    public IBinder onUnBind(Intent arg0) {
        return null;
    }

}

P.S apk was succefully installed in the emulator and button is clickable. It just wont' play the music.

P.Sk已成功安装在模拟器中,按钮可单击。它只是不会播放音乐。

3 个解决方案

#1


0  

Your code seems fine, perhaps do you add service to your Manifest?

您的代码似乎很好,或许您可以为您的Manifest添加服务?

<service android:enabled="true" android:name=".MusicPlayService" />

[

Welcome to programming in Android, the best way to debug Android Code is by adding logs to your codes. You can use Log.d, Log.e etc to print the value of the variable pass by methods.

欢迎使用Android编程,调试Android代码的最佳方法是在代码中添加日志。您可以使用Log.d,Log.e等通过方法打印变量pass的值。

]

#2


0  

try this out:

试试这个:

1: the code

1:代码

mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
mediaPlayer.start();

#3


0  

you can try

你可以试试

mediaPlayer.setDataSource(AUDIO_STRING);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
            }
        });

You also need to permission for INTERNET if you play music online or READ_EXTERNAL_STORAGE if you play music from memory.

如果您在线播放音乐,还需要获得INTERNET的许可;如果您从内存中播放音乐,则还需要READ_EXTERNAL_STORAGE。

#1


0  

Your code seems fine, perhaps do you add service to your Manifest?

您的代码似乎很好,或许您可以为您的Manifest添加服务?

<service android:enabled="true" android:name=".MusicPlayService" />

[

Welcome to programming in Android, the best way to debug Android Code is by adding logs to your codes. You can use Log.d, Log.e etc to print the value of the variable pass by methods.

欢迎使用Android编程,调试Android代码的最佳方法是在代码中添加日志。您可以使用Log.d,Log.e等通过方法打印变量pass的值。

]

#2


0  

try this out:

试试这个:

1: the code

1:代码

mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
mediaPlayer.start();

#3


0  

you can try

你可以试试

mediaPlayer.setDataSource(AUDIO_STRING);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
            }
        });

You also need to permission for INTERNET if you play music online or READ_EXTERNAL_STORAGE if you play music from memory.

如果您在线播放音乐,还需要获得INTERNET的许可;如果您从内存中播放音乐,则还需要READ_EXTERNAL_STORAGE。