Mr.Helpy
Mr.Helpy

Reputation: 157

How to make loops in Python and in this script?

I have a script which is

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
import pyaudio
import wave
from time import sleep
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
CHUNK = 1024
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "file.wav"

audio = pyaudio.PyAudio()

# start Recording
stream = audio.open(format=FORMAT, channels=CHANNELS,
            rate=RATE, input=True,
            frames_per_buffer=CHUNK)
print "recording..."
frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print "finished recording"




# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()

waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()
sleep(10)

which records my voice for 5 seconds and saves it in a wav file. Now to loop it I have tried adding the command

while invalid_input :
    start()

at the bottom of the script and the command invalid_input = False at the top of the script with no luck. Please make me understand how to loop this script when started; after the sleep(10) command. And also please cooperate with me as I am a newbie in python

Regards,

EDIT: I think I was not clear.
I want it that once it is started and reaches the end of the script, it again goes to the top and then does it again over and over till somone kills it

Upvotes: 0

Views: 361

Answers (2)

Pythogen
Pythogen

Reputation: 640

Alright, as mentioned in the comments, you NEED to indent. Python is a coding language that uses indentation instead of end or using {} ex:

def function():
    #Do stuff

Next, I'm not sure what start() is defined as but it won't by default start your script, you need to def start(): and put the recording and saving script inside that function. And then you can call it later using start()

Lastly, your while statement is inverted. If you want to run the loop when invalid_input is false you need to while invalid_input==False:

Upvotes: 1

ryekayo
ryekayo

Reputation: 2421

To make a loop in Python, you need to indent properly. In your code, you have not indented correctly, per Python's convention:

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)
    print "finished recording"

Upvotes: 0

Related Questions