Отправка аудиофайлов каждые 60 секунд с Android на сервер Python через сокет - PullRequest
0 голосов
/ 20 марта 2019

Я застреваю при отправке аудиофайла, записанного, из приложения для Android, каждые 60 с на сервере Python через сокет.

Мне удалось отправить файл с клиента Python на сервер Python. Если отправить файл 60-х годов с клиента Python, сервер Python получит его и сохранит как один файл.

Вот код.

Client.py

#!/usr/bin/env python

import logging
import socket
import pyaudio
import time
import wave
import os

# Initialize logging
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger('Humm - Client')
logger.setLevel(logging.DEBUG)

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)

logger.addHandler(ch)


# Create the socket
logger.info('Client Socket Initialisation')
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('127.0.0.1', 4444))
logger.info('Client Socket Initiliazed')


# Audio Initialisation
logger.info('Audio Initialisation')

FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 4096
RECORD_SECONDS = 60

audio = pyaudio.PyAudio()
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)
logger.info('Audio Initialized')

# Will contain RECORD_SECOND of what the user has said
# The content will then be sent to the server
frames = bytearray()
# frames = []

try:
    while True:
        for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)) :
            # if i%50 == 0:
            #     print(i)
            data = stream.read(CHUNK)
            frames.extend(data)

        current_time = int(round(time.time() * 1000))
        waveFile = wave.open(os.path.join('client', str(current_time)), 'wb')
        waveFile.setnchannels(CHANNELS)
        waveFile.setsampwidth(audio.get_sample_size(FORMAT))
        waveFile.setframerate(RATE)
        waveFile.writeframes(frames) # (b''.join(data))
        waveFile.close()


        frames.clear()

        print(current_time)
        print("***"*50)
        print()
        print()

        logging.debug('File %s has been created', os.path.join('server', str(current_time)))
        # stream.write(data)
        client_socket.send(frames)
except KeyboardInterrupt:
    pass

logger.info('Client Shutting down')
client_socket.close()
stream.stop_stream()
stream.close()
audio.terminate()

Server.py

#!/usr/bin/env python

import logging
import pyaudio
import socket
import select
import wave
import time
import os
import threading

logging.basicConfig(level=logging.DEBUG)

# Logging initiliasation
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger('Humm_Server')
logger.setLevel(logging.DEBUG)

# fh = logging.FileHandler('humm_server.log')
# fh.setLevel(logging.DEBUG)

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# fh.setFormatter(formatter)
ch.setFormatter(formatter)

# logger.addHandler(fh)
logger.addHandler(ch)

# Audio Initialisation
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 4096
RECORD_SECONDS = 60
audio = pyaudio.PyAudio()

# Socket Initialisation
logging.info('Socket Initialisation')

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('', 4444))
server_socket.listen(5)
logging.info('Socket Initialized')

class ClientThread(threading.Thread):

    def __init__(self, ip, port, socket):

        threading.Thread.__init__(self)

        self.ip = ip
        self.port = port
        self.socket = socket

        logging.info("[+] Nouveau thread  pour %s %s" %(self.ip, self.port))

    def run(self):
        logging.info("ClientThread Run - Connection de %s %s" %(self.ip, self.port))

        while True:
            frames = bytearray()
            # data = self.socket.recv(CHUNK * int(RATE/CHUNK * RECORD_SECONDS))
            data = self.socket.recv(CHUNK * 1293)
            if not data:
                logging.debug("END.... DIRECT DATA");
                self.socket.close()
                break

            current_time = int(round(time.time() * 1000))

            waveFile = wave.open(os.path.join('server', str(current_time)), 'wb')
            waveFile.setnchannels(CHANNELS)
            waveFile.setsampwidth(audio.get_sample_size(FORMAT))
            waveFile.setframerate(RATE)
            waveFile.writeframes(frames) # (data) # (b''.join(data))
            waveFile.close()

            end = time.time()
            logging.debug('File %s has been created', os.path.join('server', str(current_time)))
            # logging.debug('Execution time %s', (end - start))


threads = []

try:
    while True:
        (client_socket, (ip, port)) = server_socket.accept()

        logging.debug("Got connection from %s - %s" %(ip, port))

        newthread = ClientThread(ip, port, client_socket)
        newthread.start()
        threads.append(newthread)

except KeyboardInterrupt:
    pass

server_socket.close()

Python - Python работает хорошо! Проблема возникает, когда я отправляю аудио au с Android на тот же сервер Python. Для одного файла, отправленного с Android, сервер Python сохранит много файлов, почти сотню файлов. Я не понимаю почему.

Вот код Android, отвечающий за отправку файла. Я использую AsynTask

class SocketCommunicationTask(_handler:SocketCommunicationHandler): AsyncTask<String, Unit, Unit>() {

    private val Log:AnkoLogger = AnkoLogger(this.javaClass)

    var handler: SocketCommunicationHandler

    lateinit var inReader:BufferedInputStream // BufferedReader
    lateinit var outWritter:DataOutputStream // BufferedWriter

    init {


        this.handler = _handler
    }


    override fun onPreExecute() {
        super.onPreExecute()

        logger.debug { "onPreExecute()" }
//        this.outWritter = BufferedWriter(OutputStreamWriter(MainApplication.instance!!.getSocket().getOutputStream()))
        this.outWritter = DataOutputStream(MainApplication.instance!!.getSocket().getOutputStream())
    }

    override fun doInBackground(vararg p0: String?) {
        logger.debug { "doInBackground()" }
        var paramFile: File = File(p0[0])
        val file: FileInputStream = FileInputStream(paramFile)
        logger.info { "DoInBackground() --- FILE.... ${paramFile.absolutePath}" }
        try {
//            this.inReader = BufferedReader(InputStreamReader(MainApplication.instance!!.getSocket().getInputStream()))
            this.inReader = BufferedInputStream(file)
//            this.outWritter = BufferedWriter(OutputStreamWriter(MainApplication.instance!!.getSocket().getOutputStream()))
//            this.outWritter = DataOutputStream(MainApplication.instance!!.getSocket().getOutputStream())

            logger.info { "File LENGTH : ${paramFile.length()} -- ${paramFile.length().toInt()}" }
            var fileBytes: ByteArray = kotlin.ByteArray(paramFile.length().toInt()) // (2646016) // (
            inReader.read(fileBytes)
            logger.info { "FILE BYTES SIZE ${fileBytes.size}"}

            outWritter.write(fileBytes) // fileBytes.single()

        } catch (ex:UnknownHostException) {
            error(ex.toString())
            this.handler.didDisconnect(ex)
        } catch (ex: IOException) {
            // error("IOException - " + ex.toString())
            logger.error(ex) { "IOException ..."}
            this.handler.didDisconnect(ex)
        } catch (ex:Exception) {
            // error("EXception - " + ex.toString())
            logger.error(ex) { "Exception..." }
//            this.handler.didDisconnect(ex)
        } finally {
            try {
//                this.handler.didDisconnect(null)
            } catch (ex:Exception) {
                // error("Exception - " + ex.toString())
                logger.error(ex) { "Exception..." }
            }
        }
    }

    override fun onProgressUpdate(vararg values: Unit?) {
        super.onProgressUpdate(*values)

        logger.debug { "onProgressUpdate()" }
    }

    override fun onPostExecute(result: Unit?) {
        super.onPostExecute(result)

        logger.debug { "onPostExecute" +
                ".+3()" }
    }

}

Когда я заметил проблему, я изменил часть кода, отправляющего файл. Я попробовал это, но все та же проблема.

        var buffer: ByteArray = kotlin.ByteArray(4096)
        var outBuffer: ByteArray = kotlin.ByteArray(646*4096)
        var bytesRead = inReader.read(buffer)
        var count: Int = 0;
        logger.info { "BYTES READ..: ${bytesRead}"}
        while (bytesRead != -1) {
            // outBuffer. Push bytesRead into outBuffer
            outBuffer += buffer
            count++
            bytesRead = inReader.read(buffer)
        }
        logger.info { "NUMBER COUNTED : ${count} ---- LENGTH : ${outBuffer.size}"}
        outWritter.write(outBuffer)

Вот где я называю задачу

timer.schedule(60000, 60000) {
    step++
    val _file: String? = recorder?.saveReconding(filename, step)
    logger.info { "TIMER... FILE... ${_file}" }

    val mSocketCommunicationTask:SocketCommunicationTask = SocketCommunicationTask(this@StartActivity)
    mSocketCommunicationTask.execute(_file)
    Thread.sleep(5000)
}

Кто-нибудь знает, как я могу решить эту проблему, пожалуйста?

...