Метод паузы не работает в речи к тексту - PullRequest
0 голосов
/ 25 октября 2019

Я пытаюсь создать приложение, которое воспроизводит, приостанавливает, воспроизводит следующую песню и воспроизводит предыдущую песню. Я использую два способа: один - использование кнопок, другой - использование речи в тексте. Кнопки одна работает нормально. При преобразовании речи в текст воспроизводите, воспроизводите предыдущую композицию и воспроизводите следующую композицию правильно, но пауза не работает.

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 ();Я думаю, что ошибка связана с этим кодом. Я поместил это дважды. Я не могу понять, где это разместить. Но, возможно, ошибка связана с другой причиной. Пожалуйста, любые предложения. Если потребуется какой-либо другой файл, я его загрузю.
Спасибо

...