Python audioop.byteswap() Examples

The following are 22 code examples of audioop.byteswap(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module audioop , or try the search function .
Example #1
Source File: sample.py    From synthesizer with GNU Lesser General Public License v3.0 6 votes vote down vote up
def from_array(cls, array_or_list: Sequence[Union[int, float]], samplerate: int, numchannels: int, name: str = "") -> 'Sample':
        assert 1 <= numchannels <= 2
        assert samplerate > 1
        if isinstance(array_or_list, list):
            try:
                array_or_list = cls.get_array(2, array_or_list)
            except OverflowError:
                array_or_list = cls.get_array(4, array_or_list)
        elif numpy:
            if isinstance(array_or_list, numpy.ndarray) and any(array_or_list):
                if not isinstance(array_or_list[0], (int, numpy.integer)):
                    raise TypeError("the sample values must be integer")
        else:
            if any(array_or_list):
                if type(array_or_list[0]) is not int:
                    raise TypeError("the sample values must be integer")
        samplewidth = array_or_list.itemsize
        frames = array_or_list.tobytes()
        if sys.byteorder == "big":
            frames = audioop.byteswap(frames, samplewidth)
        return Sample.from_raw_frames(frames, samplewidth, samplerate, numchannels, name=name) 
Example #2
Source File: wave.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def readframes(self, nframes):
        if self._data_seek_needed:
            self._data_chunk.seek(0, 0)
            pos = self._soundpos * self._framesize
            if pos:
                self._data_chunk.seek(pos, 0)
            self._data_seek_needed = 0
        if nframes == 0:
            return b''
        data = self._data_chunk.read(nframes * self._framesize)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        if self._convert and data:
            data = self._convert(data)
        self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth)
        return data

    #
    # Internal methods.
    # 
Example #3
Source File: wave.py    From odoo13-x64 with GNU General Public License v3.0 6 votes vote down vote up
def readframes(self, nframes):
        if self._data_seek_needed:
            self._data_chunk.seek(0, 0)
            pos = self._soundpos * self._framesize
            if pos:
                self._data_chunk.seek(pos, 0)
            self._data_seek_needed = 0
        if nframes == 0:
            return b''
        data = self._data_chunk.read(nframes * self._framesize)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        if self._convert and data:
            data = self._convert(data)
        self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth)
        return data

    #
    # Internal methods.
    # 
Example #4
Source File: test_audioop.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_byteswap(self):
        swapped_datas = {
            1: datas[1],
            2: packs[2](0, 0x3412, 0x6745, -0x6646, -0x81, 0x80, -1),
            3: packs[3](0, 0x563412, -0x7698bb, 0x7798ba, -0x81, 0x80, -1),
            4: packs[4](0, 0x78563412, -0x547698bb, 0x557698ba,
                        -0x81, 0x80, -1),
        }
        for w in 1, 2, 3, 4:
            self.assertEqual(audioop.byteswap(b'', w), b'')
            self.assertEqual(audioop.byteswap(datas[w], w), swapped_datas[w])
            self.assertEqual(audioop.byteswap(swapped_datas[w], w), datas[w])
            self.assertEqual(audioop.byteswap(bytearray(datas[w]), w),
                             swapped_datas[w])
            self.assertEqual(audioop.byteswap(memoryview(datas[w]), w),
                             swapped_datas[w]) 
Example #5
Source File: wave.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def readframes(self, nframes):
        if self._data_seek_needed:
            self._data_chunk.seek(0, 0)
            pos = self._soundpos * self._framesize
            if pos:
                self._data_chunk.seek(pos, 0)
            self._data_seek_needed = 0
        if nframes == 0:
            return b''
        data = self._data_chunk.read(nframes * self._framesize)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        if self._convert and data:
            data = self._convert(data)
        self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth)
        return data

    #
    # Internal methods.
    # 
Example #6
Source File: wave.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def readframes(self, nframes):
        if self._data_seek_needed:
            self._data_chunk.seek(0, 0)
            pos = self._soundpos * self._framesize
            if pos:
                self._data_chunk.seek(pos, 0)
            self._data_seek_needed = 0
        if nframes == 0:
            return b''
        data = self._data_chunk.read(nframes * self._framesize)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        if self._convert and data:
            data = self._convert(data)
        self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth)
        return data

    #
    # Internal methods.
    # 
Example #7
Source File: sample.py    From synthesizer with GNU Lesser General Public License v3.0 6 votes vote down vote up
def fadein(self, seconds: float, start_volume: float = 0.0) -> 'Sample':
        """Fade the start of the sample in from the starting volume (usually zero) in the given time."""
        if self.__locked:
            raise RuntimeError("cannot modify a locked sample")
        if not self.__frames:
            return self
        seconds = min(seconds, self.duration)
        i = self.frame_idx(seconds)
        begin = self.__frames[:i]  # we fade this chunk
        end = self.__frames[i:]
        numsamples = len(begin)/self.__samplewidth
        increase = 1.0-start_volume
        _sw = self.__samplewidth     # optimization
        _getsample = audioop.getsample   # optimization
        _incr = increase/numsamples    # optimization
        faded = Sample.get_array(_sw, [int(_getsample(begin, _sw, i)*(i*_incr+start_volume)) for i in range(int(numsamples))])
        begin = faded.tobytes()
        if sys.byteorder == "big":
            begin = audioop.byteswap(begin, self.__samplewidth)
        self.__frames = begin + end
        return self 
Example #8
Source File: sample.py    From synthesizer with GNU Lesser General Public License v3.0 6 votes vote down vote up
def fadeout(self, seconds: float, target_volume: float = 0.0) -> 'Sample':
        """Fade the end of the sample out to the target volume (usually zero) in the given time."""
        if self.__locked:
            raise RuntimeError("cannot modify a locked sample")
        if not self.__frames:
            return self
        seconds = min(seconds, self.duration)
        i = self.frame_idx(self.duration-seconds)
        begin = self.__frames[:i]
        end = self.__frames[i:]  # we fade this chunk
        numsamples = len(end)/self.__samplewidth
        decrease = 1.0-target_volume
        _sw = self.__samplewidth     # optimization
        _getsample = audioop.getsample   # optimization
        faded = Sample.get_array(_sw, [int(_getsample(end, _sw, i)*(1.0-i*decrease/numsamples)) for i in range(int(numsamples))])
        end = faded.tobytes()
        if sys.byteorder == "big":
            end = audioop.byteswap(end, self.__samplewidth)
        self.__frames = begin + end
        return self 
Example #9
Source File: test_audioop.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_byteswap(self):
        swapped_datas = {
            1: datas[1],
            2: packs[2](0, 0x3412, 0x6745, -0x6646, -0x81, 0x80, -1),
            3: packs[3](0, 0x563412, -0x7698bb, 0x7798ba, -0x81, 0x80, -1),
            4: packs[4](0, 0x78563412, -0x547698bb, 0x557698ba,
                        -0x81, 0x80, -1),
        }
        for w in 1, 2, 3, 4:
            self.assertEqual(audioop.byteswap(b'', w), b'')
            self.assertEqual(audioop.byteswap(datas[w], w), swapped_datas[w])
            self.assertEqual(audioop.byteswap(swapped_datas[w], w), datas[w])
            self.assertEqual(audioop.byteswap(bytearray(datas[w]), w),
                             swapped_datas[w])
            self.assertEqual(audioop.byteswap(memoryview(datas[w]), w),
                             swapped_datas[w]) 
Example #10
Source File: wave.py    From android_universal with MIT License 6 votes vote down vote up
def readframes(self, nframes):
        if self._data_seek_needed:
            self._data_chunk.seek(0, 0)
            pos = self._soundpos * self._framesize
            if pos:
                self._data_chunk.seek(pos, 0)
            self._data_seek_needed = 0
        if nframes == 0:
            return b''
        data = self._data_chunk.read(nframes * self._framesize)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        if self._convert and data:
            data = self._convert(data)
        self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth)
        return data

    #
    # Internal methods.
    # 
Example #11
Source File: wave.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def readframes(self, nframes):
        if self._data_seek_needed:
            self._data_chunk.seek(0, 0)
            pos = self._soundpos * self._framesize
            if pos:
                self._data_chunk.seek(pos, 0)
            self._data_seek_needed = 0
        if nframes == 0:
            return b''
        data = self._data_chunk.read(nframes * self._framesize)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        if self._convert and data:
            data = self._convert(data)
        self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth)
        return data

    #
    # Internal methods.
    # 
Example #12
Source File: wave.py    From Imogen with MIT License 6 votes vote down vote up
def readframes(self, nframes):
        if self._data_seek_needed:
            self._data_chunk.seek(0, 0)
            pos = self._soundpos * self._framesize
            if pos:
                self._data_chunk.seek(pos, 0)
            self._data_seek_needed = 0
        if nframes == 0:
            return b''
        data = self._data_chunk.read(nframes * self._framesize)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        if self._convert and data:
            data = self._convert(data)
        self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth)
        return data

    #
    # Internal methods.
    # 
Example #13
Source File: test_audioop.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_byteswap(self):
        swapped_datas = {
            1: datas[1],
            2: packs[2](0, 0x3412, 0x6745, -0x6646, -0x81, 0x80, -1),
            3: packs[3](0, 0x563412, -0x7698bb, 0x7798ba, -0x81, 0x80, -1),
            4: packs[4](0, 0x78563412, -0x547698bb, 0x557698ba,
                        -0x81, 0x80, -1),
        }
        for w in 1, 2, 3, 4:
            self.assertEqual(audioop.byteswap(b'', w), b'')
            self.assertEqual(audioop.byteswap(datas[w], w), swapped_datas[w])
            self.assertEqual(audioop.byteswap(swapped_datas[w], w), datas[w])
            self.assertEqual(audioop.byteswap(bytearray(datas[w]), w),
                             swapped_datas[w])
            self.assertEqual(audioop.byteswap(memoryview(datas[w]), w),
                             swapped_datas[w]) 
Example #14
Source File: pyDubMod.py    From AlexaBot with MIT License 6 votes vote down vote up
def read(self, size = -1):
            buffer = self.audio_reader.readframes(self.audio_reader.getnframes() if size == -1 else size)
            if not isinstance(buffer, bytes): buffer = b"" # workaround for https://bugs.python.org/issue24608

            sample_width = self.audio_reader.getsampwidth()
            if not self.little_endian: # big endian format, convert to little endian on the fly
                if hasattr(audioop, "byteswap"): # ``audioop.byteswap`` was only added in Python 3.4 (incidentally, that also means that we don't need to worry about 24-bit audio being unsupported, since Python 3.4+ always has that functionality)
                    buffer = audioop.byteswap(buffer, sample_width)
                else: # manually reverse the bytes of each sample, which is slower but works well enough as a fallback
                    buffer = buffer[sample_width - 1::-1] + b"".join(buffer[i + sample_width:i:-1] for i in range(sample_width - 1, len(buffer), sample_width))

            # workaround for https://bugs.python.org/issue12866
            if self.samples_24_bit_pretending_to_be_32_bit: # we need to convert samples from 24-bit to 32-bit before we can process them with ``audioop`` functions
                buffer = b"".join("\x00" + buffer[i:i + sample_width] for i in range(0, len(buffer), sample_width)) # since we're in little endian, we prepend a zero byte to each 24-bit sample to get a 32-bit sample
            if self.audio_reader.getnchannels() != 1: # stereo audio
                buffer = audioop.tomono(buffer, sample_width, 1, 1) # convert stereo audio data to mono
            return buffer 
Example #15
Source File: sample.py    From synthesizer with GNU Lesser General Public License v3.0 5 votes vote down vote up
def modulate_amp(self, modulation_source: Union[Oscillator, Sequence[float], 'Sample', Iterator[float]]) -> 'Sample':
        """
        Perform amplitude modulation by another waveform or oscillator.
        You can use a Sample (or array of sample values) or an oscillator as modulator.
        If you use a Sample (or array), it will be cycled if needed and its maximum amplitude
        is scaled to be 1.0, effectively using it as if it was an oscillator.
        """
        if self.__locked:
            raise RuntimeError("cannot modify a locked sample")
        frames = self.get_frame_array()
        if isinstance(modulation_source, (Sample, list, array.array)):
            # modulator is a waveform, turn that into an 'oscillator' ran
            if isinstance(modulation_source, Sample):
                modulation_source = modulation_source.get_frame_array()
            biggest = max(max(modulation_source), abs(min(modulation_source)))
            actual_modulator = (v/biggest for v in itertools.cycle(modulation_source))   # type: ignore
        elif isinstance(modulation_source, Oscillator):
            actual_modulator = itertools.chain.from_iterable(modulation_source.blocks())    # type: ignore
        else:
            actual_modulator = iter(modulation_source)  # type: ignore
        for i in range(len(frames)):
            frames[i] = int(frames[i] * next(actual_modulator))
        self.__frames = frames.tobytes()
        if sys.byteorder == "big":
            self.__frames = audioop.byteswap(self.__frames, self.__samplewidth)
        return self 
Example #16
Source File: wave.py    From android_universal with MIT License 5 votes vote down vote up
def writeframesraw(self, data):
        if not isinstance(data, (bytes, bytearray)):
            data = memoryview(data).cast('B')
        self._ensure_header_written(len(data))
        nframes = len(data) // (self._sampwidth * self._nchannels)
        if self._convert:
            data = self._convert(data)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        self._file.write(data)
        self._datawritten += len(data)
        self._nframeswritten = self._nframeswritten + nframes 
Example #17
Source File: wave.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def writeframesraw(self, data):
        if not isinstance(data, (bytes, bytearray)):
            data = memoryview(data).cast('B')
        self._ensure_header_written(len(data))
        nframes = len(data) // (self._sampwidth * self._nchannels)
        if self._convert:
            data = self._convert(data)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        self._file.write(data)
        self._datawritten += len(data)
        self._nframeswritten = self._nframeswritten + nframes 
Example #18
Source File: wave.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def writeframesraw(self, data):
        if not isinstance(data, (bytes, bytearray)):
            data = memoryview(data).cast('B')
        self._ensure_header_written(len(data))
        nframes = len(data) // (self._sampwidth * self._nchannels)
        if self._convert:
            data = self._convert(data)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        self._file.write(data)
        self._datawritten += len(data)
        self._nframeswritten = self._nframeswritten + nframes 
Example #19
Source File: wave.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def writeframesraw(self, data):
        if not isinstance(data, (bytes, bytearray)):
            data = memoryview(data).cast('B')
        self._ensure_header_written(len(data))
        nframes = len(data) // (self._sampwidth * self._nchannels)
        if self._convert:
            data = self._convert(data)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        self._file.write(data)
        self._datawritten += len(data)
        self._nframeswritten = self._nframeswritten + nframes 
Example #20
Source File: wave.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def writeframesraw(self, data):
        if not isinstance(data, (bytes, bytearray)):
            data = memoryview(data).cast('B')
        self._ensure_header_written(len(data))
        nframes = len(data) // (self._sampwidth * self._nchannels)
        if self._convert:
            data = self._convert(data)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        self._file.write(data)
        self._datawritten += len(data)
        self._nframeswritten = self._nframeswritten + nframes 
Example #21
Source File: wave.py    From Imogen with MIT License 5 votes vote down vote up
def writeframesraw(self, data):
        if not isinstance(data, (bytes, bytearray)):
            data = memoryview(data).cast('B')
        self._ensure_header_written(len(data))
        nframes = len(data) // (self._sampwidth * self._nchannels)
        if self._convert:
            data = self._convert(data)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        self._file.write(data)
        self._datawritten += len(data)
        self._nframeswritten = self._nframeswritten + nframes 
Example #22
Source File: wave.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def writeframesraw(self, data):
        if not isinstance(data, (bytes, bytearray)):
            data = memoryview(data).cast('B')
        self._ensure_header_written(len(data))
        nframes = len(data) // (self._sampwidth * self._nchannels)
        if self._convert:
            data = self._convert(data)
        if self._sampwidth != 1 and sys.byteorder == 'big':
            data = audioop.byteswap(data, self._sampwidth)
        self._file.write(data)
        self._datawritten += len(data)
        self._nframeswritten = self._nframeswritten + nframes