首页 > 解决方案 > Java,Android 我的 MediaPlayer API 无法启动

问题描述

我是一名新程序员,我编写了一个MediaPlayerAPI,但该start()函数不起作用。

public class PlaySound {

    public Uri defaultAlarmAlertUri = Settings.System.DEFAULT_ALARM_ALERT_URI;
    public int sound = R.raw.a;
    public static MediaPlayer mediaPlayer;
    private Context context;
    private Uri uri;
    int playSound;
    private Boolean playing;
    public PlaySound(Context context){
        this.context = context;
        playing = false;
        if(mediaPlayer != null){
            playing = mediaPlayer.isPlaying();
        }
        playSound = 0;

        uri = defaultAlarmAlertUri;
    }
    public PlaySound setSound(Uri uri){
        this.uri = uri;
        return this;
    }
    public PlaySound setSound(int uri){
        this.playSound = uri;
        return this;
    }
    public PlaySound start() {

        if (uri != null && playSound != 0) {
            mediaPlayer = MediaPlayer.create(context, uri);
        } else {
            mediaPlayer = MediaPlayer.create(context, playSound);
        }
        playing = true;
        mediaPlayer.stop();
        return this;
    }
    public Boolean isPlaying(){
        return playing;
    }
    public PlaySound stop(){
        if(mediaPlayer != null &&isPlaying()) {
            mediaPlayer.reset();
            mediaPlayer.stop();
        }
        return this;
    }
}

标签: javaandroid

解决方案


我发现了错误。

public class PlaySound {

public Uri defaultAlarmAlertUri = Settings.System.DEFAULT_ALARM_ALERT_URI;
public int sound = R.raw.a;
public static MediaPlayer mediaPlayer;
private Context context;
private Uri uri;
int playSound;
private Boolean playing;
public PlaySound(Context context){
    this.context = context;
    playing = false;
    if(mediaPlayer != null){
        playing = mediaPlayer.isPlaying();
    }
    playSound = 0;

    uri = defaultAlarmAlertUri;
}
public PlaySound setSound(Uri uri){
    this.uri = uri;
    return this;
}
public PlaySound setSound(int uri){
    this.playSound = uri;
    return this;
}
public PlaySound start() {

    if (uri != null && playSound == 0) {
        mediaPlayer = MediaPlayer.create(context, uri);
    } else {
        mediaPlayer = MediaPlayer.create(context, playSound);
    }
    playing = true;
    mediaPlayer.start();
    return this;
}
public Boolean isPlaying(){
    return playing;
}
public PlaySound stop(){
    if(mediaPlayer != null &&isPlaying()) {
        mediaPlayer.reset();
        mediaPlayer.stop();
    }
    return this;
}

}


推荐阅读