暂停方法不适用于语音到文本

时间:2019-10-25 15:05:18

标签: android android-mediaplayer speech-to-text

我正在尝试制作一个可以播放,暂停,播放下一首歌曲和播放上一首歌曲的应用。我使用两种方式:-一种使用按钮,另一种使用语音转文本。 按钮一个工作正常。在文本语音播放,播放,播放前一首歌曲和播放下一首歌曲的过程中,工作正常,但暂停不起作用。

package com.example.musicaldelight;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class PlayMusic extends AppCompatActivity {

private RelativeLayout parentRelativeLayout;

private TextToSpeech mytexttospeech;
private SpeechRecognizer speechRecognition;

private ImageView playPauseBtn, nextBtn, previousBtn;
private TextView songNameTxt;

private ImageView imageView;
private RelativeLayout lowerRelativeLayout;

private MediaPlayer mymMediaPlayer;
private int position;
private ArrayList<File> mySongs;
private String mSongName;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.play_music);

    playPauseBtn=findViewById(R.id.play_pause_btn);
    nextBtn=findViewById(R.id.next_btn);
    previousBtn=findViewById(R.id.previous_btn);
    imageView=findViewById(R.id.logo);

    lowerRelativeLayout=findViewById(R.id.lower);
    songNameTxt=findViewById(R.id.songName);

    validateReceiveValuesAndStartPlaying();
    imageView.setImageResource(R.drawable.logo);

    playPauseBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            playPauseSong();
        }
    });

    previousBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mymMediaPlayer.getCurrentPosition()>0)
            {
                playPreviousSong();
            }
        }
    });

    nextBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mymMediaPlayer.getCurrentPosition()>0)
            {
                playNextSong();
            }
        }
    });

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
            speechRecognition.startListening(intent);

            **initializeTextToSpeech();
            initializeSpeechRecognizer();**

        }
    });
    **initializeTextToSpeech();
    initializeSpeechRecognizer();**
}

private void validateReceiveValuesAndStartPlaying()
{

    releaseMediaPlayer();
    Intent intent=getIntent();

    Bundle bundle=intent.getExtras();

    mySongs=(ArrayList)bundle.getParcelableArrayList("song");
    mSongName=mySongs.get(position).getName();
    String songName=intent.getStringExtra("name");

    songNameTxt.setText(songName);
    songNameTxt.setSelected(true);

    position=bundle.getInt("position",0);

    Uri uri=Uri.parse(mySongs.get(position).toString());

    mymMediaPlayer=MediaPlayer.create(PlayMusic.this,uri);
    mymMediaPlayer.start();

}

private void releaseMediaPlayer() {

    if (mymMediaPlayer != null) {

        mymMediaPlayer.release();
        mymMediaPlayer = null;
    }
}



public void playPauseSong()
{
    imageView.setBackgroundResource(R.drawable.four);
    if(mymMediaPlayer.isPlaying())
    {

        playPauseBtn.setImageResource(R.drawable.play);
        mymMediaPlayer.pause();
    }
    else
    {

        playPauseBtn.setImageResource(R.drawable.pause);
        mymMediaPlayer.start();
        imageView.setBackgroundResource(R.drawable.four);
    }
}

@Override
public void onBackPressed() {
    releaseMediaPlayer();
    super.onBackPressed();
}


public void playNextSong()
{
    mymMediaPlayer.pause();
    mymMediaPlayer.stop();
    mymMediaPlayer.release();


    position=((position+1)%mySongs.size());

    Uri uri=Uri.parse(mySongs.get(position).toString());

    mymMediaPlayer=MediaPlayer.create(PlayMusic.this,uri);

    mSongName=mySongs.get(position).toString();
    songNameTxt.setText(mSongName);
    mymMediaPlayer.start();

    imageView.setBackgroundResource(R.drawable.three);

    if(mymMediaPlayer.isPlaying())
    {
        playPauseBtn.setImageResource(R.drawable.pause);
    }
    else
    {
        playPauseBtn.setImageResource(R.drawable.play);
        imageView.setBackgroundResource(R.drawable.five);
    }

}

public void playPreviousSong()
{
    mymMediaPlayer.pause();
    mymMediaPlayer.stop();
    mymMediaPlayer.release();


    position=((position-1)<0?(mySongs.size()-1):(position-1));

    Uri uri=Uri.parse(mySongs.get(position).toString());

    mymMediaPlayer=MediaPlayer.create(PlayMusic.this,uri);

    mSongName=mySongs.get(position).toString();
    songNameTxt.setText(mSongName);
    mymMediaPlayer.start();

    imageView.setBackgroundResource(R.drawable.two);

    if(mymMediaPlayer.isPlaying())
    {
        playPauseBtn.setImageResource(R.drawable.pause);
    }
    else
    {
        playPauseBtn.setImageResource(R.drawable.play);
        imageView.setBackgroundResource(R.drawable.five);
    }

}



public void initializeSpeechRecognizer() {
    if(SpeechRecognizer.isRecognitionAvailable(this))
    {
        speechRecognition=SpeechRecognizer.createSpeechRecognizer(this);
        speechRecognition.setRecognitionListener(new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle params) {

            }

            @Override
            public void onBeginningOfSpeech() {

            }

            @Override
            public void onRmsChanged(float rmsdB) {

            }

            @Override
            public void onBufferReceived(byte[] buffer) {

            }

            @Override
            public void onEndOfSpeech() {

            }

            @Override
            public void onError(int error) {

            }

            @Override
            public void onResults(Bundle results) {

                List<String> result=results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                //recognizer returns multiple results
                processResult(result.get(0));
                //pick result with highest score
            }

            @Override
            public void onPartialResults(Bundle partialResults) {

            }

            @Override
            public void onEvent(int eventType, Bundle params) {

            }
        });
    }
}

public void processResult(String command) {
    command=command.toLowerCase();


    if(command.indexOf("play")!=-1){

        playPauseSong();

    }

    if(command.indexOf("pause")!=-1){

        playPauseSong();
    }

    if(command.indexOf("next")!=-1){

        playNextSong();
    }

    if(command.indexOf("previous")!=-1){

        playPreviousSong();
    }




}


public void initializeTextToSpeech() {

    mytexttospeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if(mytexttospeech.getEngines().size()==0)
            {
                Toast.makeText(PlayMusic.this,"There is no TTS engine on your device",Toast.LENGTH_LONG).show();
                finish();
            }
            else
            {
                mytexttospeech.setLanguage(Locale.US);
            }
        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}



@Override
protected void onPause() {
    super.onPause();
    mytexttospeech.shutdown();
}

@Override
protected void onDestroy() {


    //Close the Text to Speech Library
    if(mytexttospeech != null) {

        mytexttospeech.stop();
        mytexttospeech.shutdown();

    }
    super.onDestroy();
}

}

我已经标记了一个区域
initializeTextToSpeech();
initializeSpeechRecognizer(); 我认为错误是由于此代码引起的。我把它放了两次。我无法理解将其放置在何处。但是也许错误是由于其他原因造成的。请任何建议。如果需要其他文件,我将其上传。
谢谢

0 个答案:

没有答案