Text to Speech 不适用于与 NFC 相关的应用程序

Text to Speech not working on Application relating to NFC

免责声明:我对 Android Studio 和 App Development 非常陌生,因此代码可能没有组织

我目前正在尝试开发一个应用程序,当您在其中扫描带有纯文本的 NFC 标签时,它会通过 texttospeech(无按钮)大声说出文本。但是,当我尝试扫描 NFC 标签时,出现了文本,但文本转语音功能不起作用。

这是我的 MainActivity:

public class MainActivity extends AppCompatActivity {
    public static final String Error_Detected = "No NFC Tag Detected";
    public static final String Write_Success = "Text Written Successfully!";
    public static final String Write_Error = "Error during Writing, Try Again!";
    NfcAdapter nfcAdapter;
    PendingIntent pendingIntent;
    IntentFilter writingTagFilters[];
    boolean writeMode;
    Tag myTag;
    Context context;
    TextView edit_message;
    TextView nfc_contents;
    Button ActivateButton;
    TextToSpeech mTTS;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    edit_message = (TextView) findViewById(R.id.edit_message);
    nfc_contents = (TextView) findViewById(R.id.nfc_contents);
    ActivateButton = findViewById(R.id.ActivateButton);
    context = this;


    ActivateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                if(myTag ==null) {
                    Toast.makeText(context, Error_Detected, Toast.LENGTH_LONG).show();
                } else {
                    write("PlainText|"+edit_message.getText().toString(), myTag);
                    Toast.makeText(context, Write_Success, Toast.LENGTH_LONG ).show();
                }
            } catch (IOException e) {
                Toast.makeText(context, Write_Error, Toast.LENGTH_LONG ).show();
                e.printStackTrace();
            } catch (FormatException e) {
                Toast.makeText(context, Write_Error, Toast.LENGTH_LONG ).show();
                e.printStackTrace();
            }
        }
    });
    mTTS = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            String toSpeak = edit_message.getText().toString().trim();
            if (status != TextToSpeech.ERROR){
                //if there is no error then set language
                mTTS.setLanguage(Locale.UK);
            }
            else {
                Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
            }
            {
                Toast.makeText(MainActivity.this, toSpeak, Toast.LENGTH_SHORT).show();
                //speak the text
                mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
            }
        }
    });
    nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if(nfcAdapter == null){
        Toast.makeText(this, "This device does not support NFC", Toast.LENGTH_SHORT).show();
        finish();
    }
    readFromIntent(getIntent());
    pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
    writingTagFilters = new IntentFilter[] { tagDetected };
}
private void readFromIntent(Intent intent) {
    String action = intent.getAction();
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
        || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
        || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage[] msgs = null;
        if (rawMsgs != null) {
            msgs = new NdefMessage [rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++) {
                msgs[i] = (NdefMessage) rawMsgs[i];
            }
        }
        buildTagViews(msgs);
    }
}
private void buildTagViews(NdefMessage[] msgs) {
    if (msgs == null || msgs.length == 0) return;

    String text ="";

    byte[] payload = msgs[0].getRecords()[0].getPayload();
    String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
    int languageCodeLength = payload[0] & 0063;

    try {
        text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
    } catch (UnsupportedEncodingException e) {
        Log.e("UnsupportedEncoding", e.toString());
    }

    nfc_contents.setText("NFC Content: " + text);
}
private void write(String text, Tag tag) throws IOException, FormatException {
    NdefRecord[] records = { createRecord(text) };
    NdefMessage message = new NdefMessage(records);
    Ndef ndef = Ndef.get(tag);

    ndef.connect();

    ndef.writeNdefMessage(message);

    ndef.close();
}
private NdefRecord createRecord(String text) throws UnsupportedEncodingException {
    String lang        ="en";
    byte[] textBytes   =text.getBytes();
    byte[] langBytes   =lang.getBytes("US-ASCII");
    int    langLength  =langBytes.length;
    int    textLength  =textBytes.length;
    byte[] payload     =new byte[1 + langLength + textLength];

    payload[0] = (byte) langLength;


    System.arraycopy(langBytes, 0, payload, 1, langLength);
    System.arraycopy(textBytes, 0, payload, 1+langLength,textLength);

    NdefRecord recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);

    return recordNFC;
}


@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    readFromIntent(intent);
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
        myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    }
}


@Override
public void onPause(){
    super.onPause();
    WriteModeOff();
}

@Override
public void onResume(){
    super.onResume();
    WriteModeOn();
}

private void WriteModeOn(){
    writeMode = true;
    nfcAdapter.enableForegroundDispatch(this, pendingIntent, writingTagFilters, null);
}

private void WriteModeOff(){
    writeMode = false;
    nfcAdapter.disableForegroundDispatch(this);
}
}

我对 TextToSpeechonInit 方法中的理解你只需要设置文本到语音引擎,它不会监视特定的小部件并说出其中的所有内容并且每次都这样做它改变了。

让它说出存储在 NFC 卡上的文本

buildTagViews方法中nfc_contents.setText("NFC Content: " + text);行后添加

mTTS.speak(text, TextToSpeech.QUEUE_FLUSH, null);

因为目前您从未指示文本转语音引擎说出 NFC 卡上的内容。因为目前你只是在你从 xml 初始化它之后指示文本到语音引擎说出 TextView 中的单词(所以很可能是空的)。

您也可以删除下面 onInit 中的代码,因为它是多余的(除非您在布局 xml 中为编辑小部件设置了一些文本)并且有额外的 {}

{
   Toast.makeText(MainActivity.this, toSpeak, Toast.LENGTH_SHORT).show();
   //speak the text
   mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}