0

I have a function that can generate WAV audio frames into a list. Is there any way I can play audio from that list without using an intermediate file to generate an AudioSegment object?

EDIT: For reference, this is my code.

Noam Barnea
  • 23
  • 1
  • 7

2 Answers2

0

I managed to solve this by using a BytesIO object. Since my library uses wave.open, I can just input an IO-like object to save to and read from. I'm not sure that this is the most pythonic answer, but that is what I used.

Noam Barnea
  • 23
  • 1
  • 7
  • that's what IO objects are for, so unleass pydub already provides a documented way to solve your problem this is probably the pythonic solution indeed. – bruno desthuilliers Dec 13 '18 at 15:40
0

I suggest instantiating AudioSegment() objects directly like so:

from pydub import AudioSegment

sound = AudioSegment(
    # raw audio data (bytes)
    data=b'…',

    # 2 byte (16 bit) samples
    sample_width=2,

    # 44.1 kHz frame rate
    frame_rate=44100,

    # stereo
    channels=2
)

addendum: I see you're generating sound in your linked code snippet. You may be interested in pydub's audio generators

from pydub.generators import Sine
from pydub import AudioSegment

sine_generator = Sine(300)

# 0.1 sec silence
silence = AudioSegment.silent(duration=100)
dot = sine_generator.to_audio_segment(duration=150)
dash = sine_generator.to_audio_segment(duration=300)

signal = [dot, dot, dot, dash, dash, dash, dot, dot, dot]

output = AudioSegment.empty()
for piece in signal:
    output += piece + silence

and one final note: iteratively extending an AudioSegment like this can get slow. You might want to do something like this Mixer example

Jiaaro
  • 74,485
  • 42
  • 169
  • 190
  • Thanks for the advice on instantiating the AudioSegment with data of its own, didn't know I can do that. On the matter of using PyDub generators in my library, I think I'd rather not. I want to make it as independent as possible and understand the math behind sound at the same time. – Noam Barnea Dec 15 '18 at 00:52