Python Forum
Python 2 to Python 3 Struct Issue
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python 2 to Python 3 Struct Issue
#1
I'm trying to get the following code to work in Python 3. It is fine in Python 2. I have changed the xranges to range, but there is a problem with this line: data = ''.join(struct.pack('f', samp) for samp in tone):

Error:
sequence item 0: expected str instance, bytes found.
I found this answer but couldn't work out how to apply it to my situation. Any help much appreciated.
    import math
    import struct
    import pyaudio

    def play_tone(frequency, amplitude, duration, fs, stream):
        N = int(fs / frequency)
        T = int(frequency * duration)  # repeat for T cycles
        dt = 1.0 / fs
        # 1 cycle
        tone = (amplitude * math.sin(2 * math.pi * frequency * n * dt)
                for n in xrange(N))
        # todo: get the format from the stream; this assumes Float32
        data = ''.join(struct.pack('f', samp) for samp in tone)
        for n in xrange(T):
            stream.write(data)

    fs = 48000
    p = pyaudio.PyAudio()
    stream = p.open(
        format=pyaudio.paFloat32,
        channels=1,
        rate=fs,
        output=True)

    # play the C major scale
    scale = [130.8, 146.8, 164.8, 174.6, 195.0, 220.0, 246.9, 261.6]
    for tone in scale:
        play_tone(tone, 0.5, 0.75, fs, stream)

    # up an octave
    for tone in scale[1:]:
        play_tone(2*tone, 0.5, 0.75, fs, stream)

    stream.close()
    p.terminate()
Reply


Messages In This Thread
Python 2 to Python 3 Struct Issue - by robin73 - Jun-16-2018, 09:35 PM
RE: Python 2 to Python 3 Struct Issue - by Larz60+ - Jun-16-2018, 10:05 PM
RE: Python 2 to Python 3 Struct Issue - by robin73 - Jun-16-2018, 10:47 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Issue with uninstalling Python that is driving me crazy traxus 0 368 Mar-30-2024, 04:37 PM
Last Post: traxus
  Facing issue in python regex newline match Shr 6 1,715 Oct-25-2023, 09:42 AM
Last Post: Shr
  Python C Extension Module loading issue on Cygwin mesibo 0 792 Sep-22-2023, 05:41 AM
Last Post: mesibo
  Python Struct Question, decimal 10, \n and \x0a. 3python 2 774 Aug-11-2023, 09:29 AM
Last Post: 3python
  Python venv and PIP version issue JanOlvegg 2 1,490 Feb-22-2023, 02:22 AM
Last Post: JanOlvegg
  Python List Issue Aggie64 5 1,893 Jun-30-2022, 09:15 PM
Last Post: Aggie64
  Issue while using ctypes in python GiggsB 6 3,069 Mar-27-2022, 03:38 AM
Last Post: GiggsB
  MAC Python IDLE issue shadow12 4 2,772 Oct-29-2021, 12:22 AM
Last Post: shadow12
Big Grin Newbie to Python - input and branching issue Sherine 3 2,368 Jul-31-2021, 01:09 AM
Last Post: Pedroski55
  Python issue - Data science - Help is needed yovel 2 2,153 Jul-29-2021, 04:27 PM
Last Post: yovel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020