Можно ли автоматически создавать субтитры из аудиофайла с помощью MediaPlayer? - PullRequest
0 голосов
/ 03 июля 2019

Ниже приведен мой код;

Можно ли программно создать файл mp3 в файл .srt?

    holder.llView.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {
                MediaPlayer mediaPlayer = new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(filePathList.get(position));
                    mediaPlayer.prepare();

                   //mediaPlayer.addTimedTextSource(subTitleSrc, MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);
                   //int textTrackIndex = findTrackIndexFor(
                   //MediaPlayer.TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT,
                   //mediaPlayer.getTrackInfo());
                   //if (textTrackIndex >= 0) {
                   //   mediaPlayer.selectTrack(textTrackIndex);
                   //} else {
                   //  Log.w("test", "Cannot find text track!");
                    //}

                    // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    // mediaPlayer.setOnTimedTextListener(new MediaPlayer.OnTimedTextListener() {
                    //@Override
                    //public void onTimedText(final MediaPlayer mediaPlayer, final TimedText timedText) {
                    //if (timedText != null) {
                    //Log.d("test", "subtitle: " + timedText.getText());
                    // }
                     //       }
                     // });
                      // }
                   mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

                } catch (IOException e) {
                    e.printStackTrace();
                }
                mediaPlayer.start();
            }
        });

Ниже код для команды ffmpeg;

  String cmd=  "ffmpeg -i"+ filePathList.get(position).substring(filePathList.get(position).lastIndexOf("/")+1);
                    FFmpeg ffmpeg = FFmpeg.getInstance(CountryListActivity.this);
                    try {
                        // to execute "ffmpeg -version" command you just need to pass "-version"
                        ffmpeg.execute(new String[]{cmd}, new ExecuteBinaryResponseHandler() {

                            @Override
                            public void onStart() {
                                Log.e("!!!!!!!!!",""+filePathList.get(position));
                            }

                            @Override
                            public void onProgress(String message) {
                                Log.e("message..............",""+message);
                            }

                            @Override
                            public void onFailure(String message) {
                                Log.e("messageeeeeeeee..............",""+message);
                            }

                            @Override
                            public void onSuccess(String message) {
                                Log.e("messageeeeeeewwwwwwwwwwwee..............",""+message);
                            }

                            @Override
                            public void onFinish() {
                                Log.e("messagewwwewreeeeeeee..............","");
                            }
                        });
                    } catch (FFmpegCommandAlreadyRunningException e) {
                        // Handle if FFmpeg is already running
                        e.printStackTrace();
                    }

1 Ответ

1 голос
/ 03 июля 2019

То, что вы в основном ищете, Речь к тексту. Как вы упомянули в своем вопросе, что вы уже записали аудио. Вы можете использовать Google Speech To Text API для получения текста из аудио. Вот пример кода от Google

// Imports the Google Cloud client library
import com.google.cloud.speech.v1.RecognitionAudio;
import com.google.cloud.speech.v1.RecognitionConfig;
import com.google.cloud.speech.v1.RecognitionConfig.AudioEncoding;
import com.google.cloud.speech.v1.RecognizeResponse;
import com.google.cloud.speech.v1.SpeechClient;
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1.SpeechRecognitionResult;
import com.google.protobuf.ByteString;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class QuickstartSample {

  /**
   * Demonstrates using the Speech API to transcribe an audio file.
   */
  public static void main(String... args) throws Exception {
    // Instantiates a client
    try (SpeechClient speechClient = SpeechClient.create()) {

      // The path to the audio file to transcribe
      String fileName = "./resources/audio.raw";

      // Reads the audio file into memory
      Path path = Paths.get(fileName);
      byte[] data = Files.readAllBytes(path);
      ByteString audioBytes = ByteString.copyFrom(data);

      // Builds the sync recognize request
      RecognitionConfig config = RecognitionConfig.newBuilder()
          .setEncoding(AudioEncoding.LINEAR16)
          .setSampleRateHertz(16000)
          .setLanguageCode("en-US")
          .build();
      RecognitionAudio audio = RecognitionAudio.newBuilder()
          .setContent(audioBytes)
          .build();

      // Performs speech recognition on the audio file
      RecognizeResponse response = speechClient.recognize(config, audio);
      List<SpeechRecognitionResult> results = response.getResultsList();

      for (SpeechRecognitionResult result : results) {
        // There can be several alternative transcripts for a given chunk of speech. Just use the
        // first (most likely) one here.
        SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
        System.out.printf("Transcription: %s%n", alternative.getTranscript());
      }
    }
  }
}

Чтобы добавить его в свой проект Android. Для добавления GoogleCloud вы можете посетить или напрямую загрузить JAR

...