3

I'm trying to play a .wav file that is sent via Socket Server on Android live.

The following solution works for Linux when I use pyaudio:

Client.py

p = pyaudio.PyAudio()
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                output=True,
                frames_per_buffer=CHUNK)
while True:
    res=self.ClientSocket.recv(1024).decode()
    sys.stdout.flush()
    data="1"
    while data != "":
        audio_bytes = self.ClientSocket.recv(1024)
        stream.write(audio_bytes)
stream.stop_stream()
stream.close()
p.terminate()

Server.py

class Stream_Thread(Thread):
    def init(self, conn, ip, port, filename, thread_id):
        Thread.init(self)
        self.conn = conn
        self.ip = ip
        self.port = port
        self.filename = filename
        self.thread_id = thread_id
        print(
            f"[ ] - Connecting to {self.ip}:{self.port}\tID: {self.thread_id}")
        print(
            f"[+] - Steam thread connected succesfully to {self.ip}:{str(self.port)}\tID: {self.thread_id}")

    def run(self):
        wf = wave.open(self.filename, 'rb')

        p = pyaudio.PyAudio()

        CHUNK = 1024
        FORMAT = pyaudio.paInt16
        CHANNELS = 2
        RATE = 44100
        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        output=True,
                        frames_per_buffer=CHUNK)

        data = 1
        while data:
            data = wf.readframes(CHUNK)
            try:
                self.conn.send(data)
            except:
                break

I Apologise for not having a reproducible example.

My issue is, you can't use pyaudio on android, and thus the above solution (that works on desktop) won't work on mobile devices.

Posts such as: Play audio files from server Android Have given be hope onto how I could make it work using jnius: (Code below from: Play sound using bytes that works on android)

from jnius import autoclass
MediaPlayer = autoclass('android.media.MediaPlayer')
AudioManager = autoclass('android.media.AudioManager')

self.sound = MediaPlayer()
self.sound.setDataSource(yourDataSource) #you can provide any data source, if its on the devie then the file path, or its url if you are playing online
self.sound.prepare()
self.sound.setLooping(False) #you can set it to true if you want to loop
self.sound.start()
# You can also use the following according to your needs
#self.sound.pause()
#self.sound.stop()
#self.sound.release()
#self.sound.getCurrentPosition()
#self.sound.getDuration()

Where I'm stuck at is, what do I put into the self.sound.setDataSource(yourDataSource) to play the 'bytes' I'm assuming this would work perfectly if I provided a path to a file, or a URL to some audio file, but what I need is to play 'bytes' that are sent to that device?

JareBear
  • 467
  • 9
  • 27

0 Answers0