def analyze_user_rec(): """Analyze the user's recording, save the audio data and pitch data to database, and send pitch data back to page.""" # cut off first 22 chars ("data:audio/wav;base64,") user_b64 = request.form.get("user_rec")[22:] user_wav = base64.b64decode(user_b64) user_recording_path = os.path.abspath('./sounds/user-rec.wav') with open(user_recording_path, 'wb') as f: f.write(user_wav) user_pitch_data = analyze_pitch(user_recording_path) # store audio data (user_b64) and user_pitch_data in db ex_id = request.form.get("ex_id") attempts = Recording.query.filter_by(ex_id=ex_id).all() if attempts: attempt_num = max(attempt.attempt_num for attempt in attempts) + 1 else: attempt_num = 1 new_rec = Recording(ex_id=ex_id, attempt_num=attempt_num, audio_data=user_b64, pitch_data=user_pitch_data) db.session.add(new_rec) db.session.commit() return jsonify(attempt=new_rec.serialize())
def post(self): post = self.request new_record = Recording(name=post.get("name", ""), playback=post.get("playback", ""), mp3=post.get("mp3", "")) new_record.put() self.response.write(new_record.key.id()) return
def post(self): post = self.request new_record = Recording( name= post.get("name", ""), playback= post.get("playback", ""), mp3 = post.get("mp3", "")) new_record.put() self.response.write(new_record.key.id()) return
def get(self, recording_id): recording = Recording.get_by_id(int(recording_id)) if recording is None: self.redirect("/") return recordings = Recording.query().fetch() self.set_template("recording.html") self.template_values["recordings"] = recordings self.template_values["recording"] = recording self.render() return
def get(self): recordings = Recording.query().fetch() self.set_template("index.html") self.template_values["recordings"] = recordings self.render() return
def load_recording(path): """Loads sample_width, bitrate, sound_data from given filename""" wf = wave.open(path, 'rb') sample_width = wf.getsampwidth() bitrate = wf.getframerate() packed_data = wf.readframes(wf.getnframes()) sound_data = unpack('<' + ('h' * wf.getnframes()), packed_data) return Recording(sample_width, bitrate, array('h', sound_data))
def put(self): post = self.request recording = Recording.get_by_id(int(post.get("id"))) if recording is not None: recording.mp3 = post.get("mp3", "") recording.put() else: self.error(404)
def analyze_user_rec(): """Analyze the user's recording, save audio data and pitch data to the database if they're logged in, and send pitch data back to page.""" ex_id = request.form.get("ex_id") # cut off first 22 chars ("data:audio/wav;base64,") user_b64 = request.form.get("user_rec")[22:] user_wav = base64.b64decode(user_b64) user_recording_path = os.path.abspath('./static/sounds/user-rec-' + str(uuid.uuid4()) + '.wav') with open(user_recording_path, 'wb') as f: f.write(user_wav) user_pitch_data = analyze_pitch(user_recording_path) os.remove(user_recording_path) attempt = {} if 'user_id' in session: attempts = Recording.query.filter_by(user_id=session['user_id'], ex_id=ex_id).all() attempt_num = 1 if attempts: attempt_num += max(attempt.attempt_num for attempt in attempts) new_rec = Recording(user_id=session['user_id'], ex_id=ex_id, attempt_num=attempt_num, audio_data=user_b64, pitch_data=user_pitch_data, created_at=datetime.datetime.now()) db.session.add(new_rec) db.session.commit() attempt = new_rec.serialize() else: attempt = { "ex_id": ex_id, "audio_data": user_b64, "pitch_data": json.loads(user_pitch_data) } return jsonify(attempt=attempt)
def recording_artist_update(artist): # remove old entries for record in Recording.selectBy(by=artist): record.destroySelf() # add new entries (if any) for recording in cdbaby.recordings(artist.name): Recording( name=recording["name"], by=artist, url=recording["url"], img_url=recording["img_url"], source=Source.byName("cdbaby"), ) for recording in amazon.recordings(artist.name): Recording( name=recording["name"], by=artist, url=recording["url"], img_url=recording["img_url"], source=Source.byName("amazon"), )
def load_recordings(): """ Load recordings info and add to database. """ ocean = Recording( name='Ocean', description= "Relaxing Ocean Sounds recording from Tanah Lot in Bali. Tanah Lot is a rocky area on the south-west coast of Bali and home to the ancient Hindu pilgrimage temple Pura Tanah Lot.", file_path='/static/audio/Indonesia_Bali_TanahLot_Ocean_Waves_SC.mp3') park = Recording( name='Park', description= "Five minutes at the Echo Park Lake in Los Angeles. You can hear birds, people, water, and traffic.", file_path= '/static/audio/USA_Los_Angeles_Echo_Park_Ambiance_People_Stereo.mp3') stream = Recording( name='Stream', description= "A flowing river has a relaxing and healing sound. Birds sing in the background while water flows.", file_path='/static/audio/Bachlauf_Binaural_Biberach.mp3') guitar = Recording( name='Guitar', description= 'Classic guitar sounds from guitarists Vito Kruger and Favio Rodriguez.', file_path= '/static/audio/USA_Instrumental_Classic_Guitar_Vito_and_Favio_Mono.mp3' ) forest = Recording( name='Forest', description= 'Listen to the therapeutic and relaxing sounds of a forest in Germany.', file_path= '/static/audio/Germany_BadenWurttemberg_Forest_Birds_MorningSounds.mp3' ) rain = Recording( name='Rain', description='Sounds of rain and thunder.', file_path= '/static/audio/Indonesia_Bali_Ubud_RainOnPalmTrees_Thunder_.mp3') db.session.add_all([ocean, park, stream, guitar, forest, rain]) db.session.commit()
def record(self): """ Record sound from mic and return the data as an array of signed shorts. Normalizes the audio, trims silence from the start and end Returns sample_size, bitrate, sound_array """ recorder = pyaudio.PyAudio() stream = recorder.open(format=self.format, channels=1, rate=self.bitrate, input=True, output=True, frames_per_buffer=self.chunk_size) sound_started = False self._print("Start. Waiting for silence...") silent_chunks = 0 while 1: # wait for silence at beginning sound_data = self._read_chunk(stream) if (self._is_silent(sound_data)): silent_chunks += 1 if (silent_chunks >= 5): break self._print("Ready...") while 1: # wait for sound sound_data = self._read_chunk(stream) if not self._is_silent(sound_data): break self._print("Recording...") result = array('h') silent_chunks = 0 chunks_per_second = self.bitrate / self.chunk_size while 1: sound_data = self._read_chunk(stream) result.extend(sound_data) if self._is_silent(sound_data): silent_chunks += 1 else: silent_chunks = 0 if silent_chunks > chunks_per_second * 5: break self._print("Done!") sample_width = recorder.get_sample_size(self.format) stream.stop_stream() stream.close() recorder.terminate() self._print("Terimming") #result = normalize_volume(result) result = self._trim(result) self._print("Done") return Recording(sample_width, self.bitrate, result)
def load_dummy_data(): """ Load dummy data to test database for testing purposes. """ salt = binascii.hexlify(os.urandom(SALT_SIZE)) denise = User( username='******', password=hashlib.sha256(os.environ['PASSWORD_ONE'].encode('utf-8') + salt).hexdigest(), salt=salt.decode('utf-8'), first_name='Denise', last_name='Codes', email='*****@*****.**') salt = binascii.hexlify(os.urandom(SALT_SIZE)) roy = User( username='******', password=hashlib.sha256(os.environ['PASSWORD_TWO'].encode('utf-8') + salt).hexdigest(), salt=salt.decode('utf-8'), first_name='Roy', last_name='Codes', email='*****@*****.**') salt = binascii.hexlify(os.urandom(SALT_SIZE)) leo = User( username="******", password=hashlib.sha256(os.environ['PASSWORD_THREE'].encode('utf-8') + salt).hexdigest(), salt=salt.decode('utf-8'), first_name='Leo', last_name='Codes', email='*****@*****.**') salt = binascii.hexlify(os.urandom(SALT_SIZE)) turing = User( username='******', password=hashlib.sha256(os.environ['PASSWORD_FOUR'].encode('utf-8') + salt).hexdigest(), salt=salt.decode('utf-8'), first_name='Turing', last_name='Codes', email='*****@*****.**') salt = binascii.hexlify(os.urandom(SALT_SIZE)) denisedenise = User( username='******', password=hashlib.sha256(os.environ['PASSWORD_FIVE'].encode('utf-8') + salt).hexdigest(), salt=salt.decode('utf-8'), first_name='Denise', last_name='Salazar', email='*****@*****.**') angels = Facility(address='100 A St', city='CityOfAngels', fac_name='fac_name_1', state='CA', zipcode=10000) devils = Facility(address='100 B St', city='CityOfDevils', fac_name='fac_name_2', state='CA', zipcode=20000) wizards = Facility(address='100 C St', city='CityOfWizards', fac_name='fac_name_3', state='CA', zipcode=30000) denise.facilities.append(angels) denise.facilities.append(devils) denise.facilities.append(wizards) roy.facilities.append(devils) roy.facilities.append(wizards) cake = Program(program_name='Cake') pudding = Program(program_name='Pudding') bread = Program(program_name='Bread') angels.programs.append(cake) angels.programs.append(pudding) angels.programs.append(bread) devils.programs.append(pudding) devils.programs.append(bread) ocean = Recording(name='Ocean', description='Ocean sounds', file_path='/static/ocean') wind = Recording(name='Wind', description='Wind sounds', file_path='/static/wind') park = Recording(name='Park', description='Park sounds', file_path='/static/park') denise.recordings.append(ocean) denise.recordings.append(wind) denise.recordings.append(park) roy.recordings.append(wind) roy.recordings.append(park) family = Message( message_type='Family', message= 'I am not feeling well. I will contact you when I start feeling better.' ) boss = Message( message_type='Co-worker', message= 'I am out sick today. Please message me if there are any immediate deliverables for today.' ) friend = Message( message_type='Friend', message= 'I really wanted to see you but I cannot visit with you today. Will get in touch when I am feeling better.' ) denise.messages.append(family) denise.messages.append(boss) denise.messages.append(friend) roy.messages.append(boss) roy.messages.append(friend) db.session.add_all([denise, roy, leo, turing, denisedenise]) db.session.commit()
def delete(self, recording_id): recording = Recording.get_by_id(int(recording_id)) if recording is not None: recording.key.delete()