jjzjj

用于带有 GSM 调制解调器 rxtx 的 IVRS 的 Java 多线程(播放语音文件使事件监听器停止工作)

coder 2024-03-04 原文

我已经实现了一个程序来使用 gsm 调制解调器接听电话。在检测到 “RING” 调用被应答时,通过从 DATA_AVAILABLE 事件处理程序内部调用函数来播放音频剪辑。但是事件处理程序在此之后停止工作。音频完成后,事件处理程序不再显示任何数据接收事件。

为什么事件监听器停止工作。从事件处理程序内部播放音频是我做错了吗?我正在考虑从 data_received 事件处理程序内部设置一个变量 true 或 false 并创建自定义事件处理程序来监听对该变量的更改以播放音频,这两者是否可以同时工作?

如何创建多线程解决方案,使串行 I/O 不被中断,并且音频播放和音频采样可以以同步方式完成以检测 dtmf 音调。 有什么办法可以不间断地监听串口事件,并在特定时间运行音频采样和音频播放的功能

在 switch 的这种情况下接受调用,线程在 play() 函数中启动

 case SerialPortEvent.DATA_AVAILABLE:

       StringBuffer sb = new StringBuffer();
       byte[] readBuffer = new byte[2048];
       try {
         while (inputStream.available() > 0) 
         {
           int numBytes = inputStream.read(readBuffer);
           sb.append(new String(readBuffer,0,numBytes));
           System.out.println(numBytes);
           System.out.println(sb);
         }
         System.out.println("Data Available");   

         if((sb.toString()).contains("RING")){
            System.out.println("Enter Inside if RING Loop");   
            //play();
            send("ATA\r\n");

            //welcomeMessage();
         }

         if((sb.toString()).contains("CARRIER")){

                  hangup();
                  //Thread.sleep(1000);
                  closePort();
                  outCommand();
                  System.out.println("Enter Inside if NO CARRIER Loop");   
         }
         //print response message
         System.out.print(sb.toString());
       } catch (IOException  e) {
       }

       break;

 public void play() {
        try {
            new Thread() {
                public void run() {
                    for(int i=0;i<1;i++)
                       welcomeMessage();
                }
            }.start();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

完整代码

package sample;

import java.io.*;
import java.util.*;
import javax.sound.sampled.*;
import javazoom.jl.player.*;
import java.io.FileInputStream;
import gnu.io.*;
import java.io.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.apache.log4j.chainsaw.Main;
import sun.audio.*;

public class GSMConnect implements SerialPortEventListener, 
 CommPortOwnershipListener {

 private static String comPort = "COM3"; // This COM Port must be connect with GSM Modem or your mobile phone
 private String messageString = "";
 private CommPortIdentifier portId = null;
 private Enumeration portList;
 private InputStream inputStream = null;
 private OutputStream outputStream = null;
 private SerialPort serialPort;
 String readBufferTrial = "";
 /** Creates a new instance of GSMConnect */
 public GSMConnect(String comm) {

   this.comPort = comm;

 }

 public boolean init() {
   portList = CommPortIdentifier.getPortIdentifiers();
   while (portList.hasMoreElements()) {
     portId = (CommPortIdentifier) portList.nextElement();
     if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
       if (portId.getName().equals(comPort)) {
           System.out.println("Got PortName");
         return true;
       }
     }
   }
   return false;
 }

 public void checkStatus() {
   send("AT+CREG?\r\n");
 }

 public void dial(String phoneNumber) {
   try {
//dial to this phone number

     messageString = "ATD" + phoneNumber + ";\r\n";
     outputStream.write(messageString.getBytes());
     System.out.println("Called ");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }

 public void send(String cmd) {
   try {
     outputStream.write(cmd.getBytes());
   } catch (IOException e) {
     e.printStackTrace();
   }
 }

 public void sendMessage(String phoneNumber, String message) {
       char quotes ='"';
   send("AT+CMGS="+quotes + phoneNumber +quotes+ "\r\n");
   try {
    Thread.sleep(2000);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
    //   send("AT+CMGS=\""+ phoneNumber +"\"\r\n");
   send(message + '\032');
   System.out.println("Message Sent");
 }

 public void hangup() {
   send("ATH\r\n");
 }
 public void welcomeMessage(){

     // open the sound file as a Java input stream
        String gongFile = "C:\\Users\\XXXX\\Desktop\\1-welcome.wav";

        }*/
        try{

            FileInputStream fis = new FileInputStream("C:\\Users\\XXXX\\Desktop\\7001110.mp3");
            Player playMP3 = new Player(fis);

            playMP3.play();
            System.out.print("welcomeMessage() Read");
            }catch(Exception e){

                System.out.println(e);

            }
 }

 public void play() {
        try {
            new Thread() {
                public void run() {
                    for(int i=0;i<1;i++)
                       welcomeMessage();
                }
            }.start();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
 public void connect() throws NullPointerException {
   if (portId != null) {
     try {
       portId.addPortOwnershipListener(this);

       serialPort = (SerialPort) portId.open("MobileGateWay", 2000);
       serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
     } catch (PortInUseException | UnsupportedCommOperationException e) {
       e.printStackTrace();
     }

     try {
       inputStream = serialPort.getInputStream();
       outputStream = serialPort.getOutputStream();

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

     try {
       /** These are the events we want to know about*/
       serialPort.addEventListener(this);
       serialPort.notifyOnDataAvailable(true);
       serialPort.notifyOnRingIndicator(true);

     } catch (TooManyListenersException e) {
       e.printStackTrace();
     }

//Register to home network of sim card

     send("ATZ\r\n");

   } else {
     throw new NullPointerException("COM Port not found!!");
   }
 }

 public void serialEvent(SerialPortEvent serialPortEvent) {
    System.out.println("serialPortEvent.getEventType()"+serialPortEvent.getEventType()); 
   switch (serialPortEvent.getEventType()) {
     case SerialPortEvent.BI:
     case SerialPortEvent.OE:
     case SerialPortEvent.FE:
     case SerialPortEvent.PE:
     case SerialPortEvent.CD:
     case SerialPortEvent.CTS:
     case SerialPortEvent.DSR:
     case SerialPortEvent.RI:
        // System.out.println("Ringing");
          if( serialPortEvent.getNewValue() ) 
          {
              System.out.println("Ring Indicator On");
          }
          else 
          {
              System.out.println("Ring Indicator Off");
          }

          break;



     case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
     case SerialPortEvent.DATA_AVAILABLE:

       StringBuffer sb = new StringBuffer();
       byte[] readBuffer = new byte[2048];
       try {
         while (inputStream.available() > 0) 
         {
           int numBytes = inputStream.read(readBuffer);
           sb.append(new String(readBuffer,0,numBytes));
           System.out.println(numBytes);
           System.out.println(sb);
         }
         System.out.println("Data Available");   

         if((sb.toString()).contains("RING")){
            System.out.println("Enter Inside if RING Loop");   
            //play();
            send("ATA\r\n");

            //welcomeMessage();
         }

         if((sb.toString()).contains("CARRIER")){

                  hangup();
                  //Thread.sleep(1000);
                  closePort();
                  outCommand();
                  System.out.println("Enter Inside if NO CARRIER Loop");   
         }
         //print response message
         System.out.print(sb.toString());
       } catch (IOException  e) {
       }

       break;
   }
 }

 public void outCommand(){
     System.out.print(readBufferTrial);
 }
 public void ownershipChange(int type) {
   switch (type) {
     case CommPortOwnershipListener.PORT_UNOWNED:
       System.out.println(portId.getName() + ": PORT_UNOWNED");
       break;
     case CommPortOwnershipListener.PORT_OWNED:
       System.out.println(portId.getName() + ": PORT_OWNED");
       break;
     case CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED:
       System.out.println(portId.getName() + ": PORT_INUSED");
       break;
   }
 }
 public void closePort(){

    serialPort.close(); 
 }

 public static void main(String args[]) {
   GSMConnect gsm = new GSMConnect(comPort);
   if (gsm.init()) {
     try {
         System.out.println("Initialization Success");
       gsm.connect();
       Thread.sleep(5000);
       gsm.checkStatus();
       Thread.sleep(5000);
   //   System.out.println("Before Auto Answer");
     //  gsm.send("ATS0=5");
    //   gsm.dial("87XXXXXSS");
   //    Thread.sleep(7500);
     //  System.out.println("After Auto Answer set");

    //   gsm.sendMessage("8XXXXXS56", "Trial Success Call me");
    //   gsm.sendMessage("80XXXXS56", "Trial Success Call me");
    //   gsm.sendMessage("8XXXXSXS6", "Trial Success Call me");
    //   Thread.sleep(5000);
     //   gsm.sendMessage("+919XXXXXXS3", "Third Msg");
     //  Thread.sleep(1000);
     //  gsm.dial("9XXXXS773");
    //   gsm.dial("871XXXXS5");
     //  Thread.sleep(1000);
     //  gsm.welcomeMessage();
    //   Thread.sleep(1000);
     //  gsm.welcomeMessage();// for turning on Echo ATE1&W

     //  Thread.sleep(20000);
      // welcomeMessage();

     //  gsm.hangup();
     //  Thread.sleep(1000);
     //  gsm.closePort();
     //  gsm.outCommand();
      // System.exit(1);

     } catch (Exception e) {
       e.printStackTrace();
     }
   } else {
     System.out.println("Can't init this card");
   }
 }
}

最佳答案

如果没有花费大量时间来重现您的环境,我可以给您两个建议,告诉您如何看待这个问题。

a) 在整个处理程序周围放置一个 try-catch Throwable——通常抛出异常会破坏事件调度器

B) 当您进入和退出您的事件处理程序时打印出一条调试语句,并确保它们是配对的,并且您在最后一次进入后获得退出——线程锁定有时会阻止 future 的事件被调度。

顺便说一下,你在一个地方有一个空的 catch 语句——那些把我吓坏了,因为它们经常以可能浪费你几天时间的方式掩盖问题。如果你绝对知道你想在那里静静地吃掉一个异常,并且你希望这个异常发生到足以污染你的日志来记录它,请发表评论这样说。

关于用于带有 GSM 调制解调器 rxtx 的 IVRS 的 Java 多线程(播放语音文件使事件监听器停止工作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32338134/

有关用于带有 GSM 调制解调器 rxtx 的 IVRS 的 Java 多线程(播放语音文件使事件监听器停止工作)的更多相关文章

  1. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  2. ruby - 如何让Ruby捕获线程中的语法错误 - 2

    我正在尝试使用ruby​​编写一个双线程客户端,一个线程从套接字读取数据并将其打印出来,另一个线程读取本地数据并将其发送到远程服务器。我发现的问题是Ruby似乎无法捕获线程内的错误,这是一个示例:#!/usr/bin/rubyThread.new{loop{$stdout.puts"hi"abc.putsefsleep1}}loop{sleep1}显然,如果我在线程外键入abc.putsef,代码将永远不会运行,因为Ruby将报告“undefinedvariableabc”。但是,如果它在一个线程内,则没有错误报告。我的问题是,如何让Ruby捕获这样的错误?或者至少,报告线程中的错误?

  3. ruby - 如何在 ruby​​ 中运行后台线程? - 2

    我是ruby​​的新手,我认为重新构建一个我用C#编写的简单聊天程序是个好主意。我正在使用Ruby2.0.0MRI(Matz的Ruby实现)。问题是我想在服务器运行时为简单的服务器命令提供I/O。这是从示例中获取的服务器。我添加了使用gets()获取输入的命令方法。我希望此方法在后台作为线程运行,但该线程正在阻塞另一个线程。require'socket'#Getsocketsfromstdlibserver=TCPServer.open(2000)#Sockettolistenonport2000defcommandsx=1whilex==1exitProgram=gets.chomp

  4. ruby - Rails 开发服务器、PDFKit 和多线程 - 2

    我有一个使用PDFKit呈现网页的pdf版本的Rails应用程序。我使用Thin作为开发服务器。问题是当我处于开发模式时。当我使用“bundleexecrailss”启动我的服务器并尝试呈现任何PDF时,整个过程会陷入僵局,因为当您呈现PDF时,会向服务器请求一些额外的资源,如图像和css,看起来只有一个线程.如何配置Rails开发服务器以运行多个工作线程?非常感谢。 最佳答案 我找到的最简单的解决方案是unicorn.geminstallunicorn创建一个unicorn.conf:worker_processes3然后使用它:

  5. ruby - Ruby 1.9.1 中的 native 线程,对我有什么好处? - 2

    所以,Ruby1.9.1现在是declaredstable.Rails应该与它一起工作,并且正在慢慢地将gem移植到它。它具有native线程和全局解释器锁(GIL)。自从GIL到位后,原生线程是否比1.9.1中的绿色线程有任何优势? 最佳答案 1.9中的线程是原生的,但它们被“放慢了速度”,一次只允许一个线程运行。这是因为如果线程真的并行运行,它会混淆现有代码。优点:IO现在在线程中是异步的。如果一个线程阻塞在IO上,那么另一个线程将继续执行直到IO完成。C扩展可以使用真正的线程。缺点:任何非线程安全的C扩展都可能存在使用Thre

  6. ruby - 使写入文件线程安全 - 2

    我在一个ruby​​文件中有一个函数可以像这样写入一个文件File.open("myfile",'a'){|f|f.puts("#{sometext}")}这个函数在不同的线程中被调用,使得像上面这样的文件写入不是线程安全的。有谁知道如何以最简单的方式使这个文件写入线程安全?更多信息:如果重要的话,我正在使用rspec框架。 最佳答案 您可以通过File#flock给锁File.open("myfile",'a'){|f|f.flock(File::LOCK_EX)f.puts("#{sometext}")}

  7. Ruby 线程与 Watir - 2

    我编写了几个类来控制我想如何处理多个网站,两者都使用类似的方法(即登录、刷新)。每个类都打开自己的WATIR浏览器实例。classSite1definitialize@ie=Watir::Browser.newenddeflogin@ie.goto"www.blah.com"endend无线程的main中的代码示例如下require'watir'require_relative'site1'agents=[]agents这工作正常,但在当前代理完成登录之前不会移动到下一个代理。我想合并多线程来处理这个问题,但似乎无法让它工作。require'watir'require_relative

  8. ruby - 在多个线程中引用类方法会导致自动加载循环依赖崩溃 - 2

    代码:threads=[]Thread.abort_on_exception=truebegin#throwexceptionsinthreadssowecanseethemthreadseputs"EXCEPTION:#{e.inspect}"puts"MESSAGE:#{e.message}"end崩溃:.rvm/gems/ruby-2.1.3@req/gems/activesupport-4.1.5/lib/active_support/dependencies.rb:478:inload_missing_constant':自动加载常量MyClass时检测到循环依赖稍加研究后,

  9. Ruby 多线程/多处理读物 - 2

    任何人都可以推荐任何详细介绍Ruby多线程/多处理的复杂性的好的多线程/处理书籍/网站吗?我尝试使用ruby​​线程,基本上在1.9vm上的无死锁代码中它在jruby中遇到了死锁。是的,我意识到差异很大(jruby没有GIL),但我想知道是否有用于ruby​​中多线程编程的策略或类集,我只需要继续阅读。旁注:从java到ruby​​必须定义是否需要重新输入锁,这有点奇怪。 最佳答案 如果你使用Ruby1.9,你可以试试Fiber,它是Ruby中线程的一大改进http://ruby-doc.org/core-1.9/classes/F

  10. ruby - 跨线程共享枚举器 - 2

    我想从不同线程调用一个公共(public)枚举器。当我执行以下操作时,enum=(0..1000).to_enumt1=Thread.newdopenum.nextsleep(1)endt2=Thread.newdopenum.nextsleep(1)endt1.joint2.join它引发了一个错误:Fibercalledacrossthreads.当enum在从t1调用一次后从t2调用时。为什么Ruby设计为不允许跨线程调用枚举器(或纤程),以及是否有其他方法可以提供类似的功能?我猜测枚举器/纤程上的操作的原子性在这里是相关的,但我不完全确定。如果这是问题所在,那么在使用时独占锁定

随机推荐