android - 在特定时间在android中启动音频剪辑

标签 android audio countdowntimer

我正在创建一个android应用程序,我想在其中将时钟滴答声放在后台,最后几秒钟也是如此。

音频持续21秒,我也希望它能在计时器的最后21秒内播放。实际计时器运行2分钟。

我正在尝试以下代码:

public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            millis = millisUntilFinished;
            if(millis == 21000){
                mp1.start();
            }
            hms = String.format("%02d:%02d", 
                    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
            timer.setText(hms);

    }

mp1在哪里:
mp1 = MediaPlayer.create(AnimalMain.this,R.raw.tick_tock);

但是什么也没玩。另外,我在日志猫中得到的错误为:
should have subtitle controller already set

我尝试了许多具有相同问题的stackoverflow链接,但无法使用它们解决它。请帮忙。

有关任何引用,请参见此处的完整代码:
package com.example.jumboquest;

import android.app.Activity;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;




import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.media.MediaPlayer;


public class AnimalMain extends Activity {

    TextView timer, roundStatus;
    ListView jum;
    ProgressBar prog;
    EditText ans;
    ToggleButton pause;
    String s,hms,hmso;
    int[] a;
    Button next;
    static long millis;
    static CountDownTimer t;
    long toggleValue;
    String[] s1 = new String[4];
    static ArrayList<String> words;
    static ArrayAdapter<String> aa;
    static int progressStatus = 0;
    //Button match;
    static long resumeTsp;
    static boolean phoneRinging = false;
    static int scorekeeper;
    static int rnd_counter;
    boolean bonus = false;
    long bonus_millis = 0;
    MediaPlayer mp1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        rnd_counter++;
        setContentView(R.layout.screen2);

        resumeTsp = 120000;
        jum = (ListView)findViewById(R.id.jum);
        ans = (EditText)findViewById(R.id.ans);
        timer = (TextView)findViewById(R.id.timer);
        roundStatus = (TextView)findViewById(R.id.desc);
        prog = (ProgressBar)findViewById(R.id.prog);
        //match = (Button) findViewById(R.id.button1);
        mp1 = MediaPlayer.create(AnimalMain.this,R.raw.tick_tock);
        roundStatus.setText("Round:" +rnd_counter);

        Intent intnt = getIntent();
        progressStatus = intnt.getIntExtra("prog", 0);

        new Thread(new Runnable(){
            public void run(){
                prog.setProgress(progressStatus);
                try{
                    Thread.sleep(5000);
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

        // Create the array list of to do items
        words = new ArrayList<String>();
        // Create the array adapter to bind the array to the listview

        aa = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,words);
        // Bind the array adapter to the listview.
        jum.setAdapter(aa);



        InputStream i = this.getResources().openRawResource(R.raw.first_round);
        String line = null;
        int currentLineNo = 1;
        int min = 1;
        int max = 49;

        int startLine = 0;
        int endLine = 0;
        Random rand = new Random();
        switch(rnd_counter){
        case 1:
            min = 1;
            max = 28;
            break;
        case 2:
            min = 32;
            max = 59;
            break;
        case 3:
            min = 63;
            max = 92;
            break;
        }

        int r = rand.nextInt((max - min) + 1) + min;

        startLine = r;
        endLine = r+3;

        BufferedReader in = null;
        try {
            in = new BufferedReader (new InputStreamReader(i));         
            //read to startLine
            while(currentLineNo<startLine) {
                if (in.readLine()==null) {
                    // oops, early end of file
                    throw new IOException("File too small");
                }
                ++currentLineNo;
            }

            int i1=0;
            //read until endLine
            while(currentLineNo<=endLine) {
                line = in.readLine();
                if (line==null) {
                    // here, we'll forgive a short file
                    // note finally still cleans up
                    return;
                }
                s1[i1]=line;
                //= new StringBuffer(line).reverse().toString();

                List<Character> jumble = new ArrayList<Character>();
                StringBuilder sample = new StringBuilder(line.length());
                for(char c : line.toCharArray()){
                    jumble.add(c);
                }
                //int flag_first = 0;
                while(jumble.size() != 0){
                    int rnd = (int)(Math.random()*jumble.size());
                    if(rnd == 0 && jumble.size() == line.length()){
                        continue;
                    }
                    else{
                        sample.append(jumble.remove(rnd));
                    }
                }

                words.add(sample.toString());
                aa.notifyDataSetChanged();
                ++i1;

                ++currentLineNo;

            }

        } catch (IOException ex) {
            System.out.println("Problem reading file.\n" + ex.getMessage());
        } finally {
            try { if (in!=null) in.close(); } catch(IOException ignore) {}
        }

        a = new int[4];
        a[0] = 0;
        a[1] = 0;
        a[2] = 0;
        a[3] = 0;


      /*  match.setOnClickListener(new OnClickListener(){
            public void onClick(View v){
                String answer = ans.getText().toString();
                if(answer.equalsIgnoreCase(s1[0])){
                    words.remove(0);
                    aa.notifyDataSetChanged();
                    words.add(0,answer);
                    aa.notifyDataSetChanged();
                }
                else if(answer.equalsIgnoreCase(s1[1])){
                    words.remove(1);
                    aa.notifyDataSetChanged();
                    words.add(1,answer);
                    aa.notifyDataSetChanged();
                }
                else if(answer.equalsIgnoreCase(s1[2])){
                    words.remove(2);
                    aa.notifyDataSetChanged();
                    words.add(2,answer);
                    aa.notifyDataSetChanged();
                }
                else if(answer.equalsIgnoreCase(s1[3])){
                    words.remove(3);
                    aa.notifyDataSetChanged();
                    words.add(3,answer);
                    aa.notifyDataSetChanged();
                }
            }
        });*/

        jum.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                        long arg3) {
                    String selected = jum.getItemAtPosition(arg2).toString();
                    s= ans.getText().toString();

                    if(s.equals(s1[arg2]))
                    {
                        a[arg2]=1;
                        //Toast.makeText(getApplicationContext(), "CORRECT!! Now Crack the Next One.. :) ", Toast.LENGTH_SHORT).show();
                        words.remove(arg2);
                        aa.notifyDataSetChanged();
                        words.add(arg2,s);
                        aa.notifyDataSetChanged();
                        arg1.setEnabled(false);

                        ans.setText("");
                        if(a[0]==1 && a[1]==1 && a[2]==1 && a[3]==1)
                        {

                                    t.cancel();
                                    if(millis >= 60000){
                                        bonus = true;
                                        bonus_millis = (millis/1000)-60;
                                    }
                                    //scorekeeper += 40;
                                    Intent i=new Intent(getApplicationContext(), AnimalDatabase.class);
                                    i.putExtra("milli", millis);
                                    i.putExtra("score", scorekeeper);
                                    i.putExtra("bonus", bonus);
                                    i.putExtra("round", rnd_counter);
                                    i.putExtra("bonus_score",bonus_millis);
                                    //i.putExtra("progress",progressStatus);
                                    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(i);
                                    //Toast.makeText(getApplicationContext(), "WELL DONE!! All the best for the quiz :) ", Toast.LENGTH_LONG).show();
                                //  finish();


                        }
                    }
                    else
                    {
                        ans.setText(s);
                        Toast.makeText(getApplicationContext(), "INCORRECT :( Try Again.. ", Toast.LENGTH_SHORT).show();
                    }

                }
            });


        TelephonyManager telephonyManager =  
                (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);  

        PhoneStateListener callStateListener = new PhoneStateListener() {  
            public void onCallStateChanged(int state, String incomingNumber)   
            {  

                if(state==TelephonyManager.CALL_STATE_RINGING){  
                    resumeTsp = millis;
                    t.cancel();
                    timer.setText("Game Paused!");
                    Toast.makeText(getApplicationContext(),"Phone Is Riging",  
                                                                   Toast.LENGTH_LONG).show();  
                }  
                if(state==TelephonyManager.CALL_STATE_OFFHOOK){  
                    Toast.makeText(getApplicationContext(),"Phone is Currently in A call",   
                                                                            Toast.LENGTH_LONG).show();  
                }  
                if(state==TelephonyManager.CALL_STATE_IDLE){  
                    t = new StartTimer(resumeTsp,1000);
                    t.start();

                }  
            }  
        };  
        telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);  

    }

    @Override
    public void onBackPressed(){
        return;
    }

    class StartTimer extends CountDownTimer{
        public StartTimer(long duration, long interval){
                super(duration, interval);
        }

        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            millis = millisUntilFinished;
            //if(millis == 21000){
            //  Toast.makeText(getApplicationContext(), String.valueOf(millis), Toast.LENGTH_SHORT).show();
            //  mp1.start();
            //}
            hms = String.format("%02d:%02d", 
                    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
            timer.setText(hms);

        }

        @Override
        public void onFinish() {
            //time up
            phoneRinging = false;
            timer.setText("TIME UP!");
            mp1.stop();
            ans.setEnabled(false);
            for(int j = 0; j<4;j++){
                timer.setText("SOLUTION:");
                words.remove(j);
                aa.notifyDataSetChanged();
                words.add(j,s1[j]);
                aa.notifyDataSetChanged();
            }
        }


    }
}

最佳答案

可以通过简单地添加延迟而不是在OnTick()中检查计时器值来完成,这将不起作用。可以通过以下方式添加延迟:

final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // Do something after 5s = 5000ms
                mp1.start();
                mp1.setLooping(true);
            }
        }, 100000);

将延迟(延迟时间)设置为您要在后台启动音频的时间,这种情况在我的情况下有效。

关于android - 在特定时间在android中启动音频剪辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27177188/

相关文章:

javascript - 如何从倒计时器获取剩余时间?

swift - 如何在倒计时器标签中显示毫秒?

java - Android 倒计时器 - 循环使用列表值重新启动计时器的 ArrayList

java - Android Eclipse 设置点击监听器错误

android - GPS 联系人位置

android - 将 Google Drive 集成到 Android 应用程序中, Unresolved 导入

android - 30 秒后在 Chronometer 中播放声音

java - 文件选取器无法筛选和选取 intent.setType ("application/excel")

audio - 从 4 位 RAW 音频转换为 WAV(或其他输出格式)

audio - 如何使用 NAudio 将两个 wav 音频文件与 30 秒的白色声音连接起来