1

I would like to split a wave file using python via reticulate in R, a sample script is extracted from Python, How to split a .wav file into multiple .wav files

 from pydub import AudioSegment
    t1 = t1 * 1000 #Works in milliseconds
    t2 = t2 * 1000
    newAudio = AudioSegment.from_wav("oldSong.wav")
    newAudio = newAudio[t1:t2]
    newAudio.export('newSong.wav', format="wav")

I did similarly using R as below:

library(dplyr)
library(tidyr)
library(reticulate)
use_python('/usr/bin/python3',required = TRUE)
py_config()
pydub.py <- import('pydub')
time.start <- as.numeric(data.df.st02[loop,'time_start'])*1000
time.end <- as.numeric(data.df.st02[loop,'time_end'])*1000
new.audio <- pydub.py$AudioSegment$from_wav('142533.wav')

But returned the following error:

> new.audio[1:2]
 Error in py_call_impl(callable, dots$args, dots$keywords) : 
  TypeError: can only concatenate list (not "int") to list 

Can anyone enlighten me on how to write [t1:t2] in R?

2
  • "I did similarly using R": please share all the code you used. Commented Mar 29, 2019 at 15:25
  • certainly @nicola Commented Mar 29, 2019 at 15:31

1 Answer 1

4

The python subset operator is a wrapper of the __getitem__ method and the : is a wrapper to create a slice object. You have to import the builtins module. Try this:

require(reticulate)
use_python('/usr/bin/python3',required = TRUE)
pydub.py <- import('pydub', convert=FALSE)
pybuiltins <- import_builtins(convert=FALSE)
new.audio <- pydub.py$AudioSegment$from_wav('142533.wav')
#important: time.start and time.end must be integer
time.start <- as.integer(1*1000)
time.end <- as.integer(2*1000)
#create a slice object
sl<-pybuiltins$slice(time.start,time.end)
new.audio_split<-new.audio$`__getitem__`(sl)
new.audio_split
#<pydub.audio_segment.AudioSegment>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.