簡體   English   中英

多個媒體播放器合二為一

[英]Multiple mediaplayers into one

我正在制作一個音板應用程序,並在Java文件中添加了許多MediaPlayer實例,以便每當我單擊CardView時就可以啟動CardView 有什么辦法可以將它們全部集成到一個媒體播放器中?

//Muziekje bingo
final MediaPlayer bingoMediaPlayer = MediaPlayer.create(this, R.raw.bingo);

final CardView bingo = (CardView) this.findViewById(R.id.play_bingo);

bingo.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        bingoMediaPlayer.start();
        bingo.setCardBackgroundColor(Color.parseColor("#707980"));
    }
});

bingoMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mp) {
        bingo.setCardBackgroundColor(Color.parseColor("#b3bac0")); // finish current activity
    }
});

//muziekje harrypotter
final MediaPlayer harrypotterMediaPlayer = MediaPlayer.create(this, R.raw.harrypotter);

final CardView harrypotter = (CardView) this.findViewById(R.id.play_harrypotter);

harrypotter.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        harrypotterMediaPlayer.start();
        harrypotter.setCardBackgroundColor(Color.parseColor("#707980"));
    }
});


    harrypotterMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mp) {
            harrypotter.setCardBackgroundColor(Color.parseColor("#b3bac0")); // finish current activity
        }
    });

    //muziekje bibet
    final MediaPlayer bibetMediaPlayer = MediaPlayer.create(this, R.raw.bibet);

    final CardView bibet = (CardView) this.findViewById(R.id.play_bibet);

    bibet.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            bibetMediaPlayer.start();
            bibet.setCardBackgroundColor(Color.parseColor("#707980"));
        }
    });



    bibetMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mp) {
            bibet.setCardBackgroundColor(Color.parseColor("#b3bac0")); // finish current activity
        }
    });

您可以編寫一個功能來播放相關的音樂文件。 這將幫助您擺脫樣板代碼。

public void playSound(int music) {
    //mContext will be your context here
    MediaPlayer.create(mContext, music).start();
}

您可以像這樣在代碼中使用此功能

bingo.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            playSound(R.raw.bingo);
            bingo.setCardBackgroundColor(Color.parseColor("#707980"));
         }
    });

harrypotter.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            playSound(R.raw.harrypotter);
            harrypotter.setCardBackgroundColor(Color.parseColor("#707980"));
        }
    });

希望對您有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM