Examples of modifying the volume of a sound file with media.py
Download Complete Example
import media
def change_volume(sound, loudness_factor):
new_sound = media.duplicateSound(sound)
for sample in media.getSamples(new_sound):
value = media.getSampleValue(sample)
media.setSampleValue(sample, value * loudness_factor)
return new_sound
def change_volume_range(sound, loudness_factor, start, end):
new_sound = media.duplicateSound(sound)
for index in range(start, end):
value = media.getSampleValueAt(new_sound, index)
media.setSampleValueAt(new_sound, index, value * loudness_factor)
return new_sound
def find_loudest(sound):
loudest = 0
samples = media.getSamples(sound)
for index in range(len(samples)):
sample = samples[index]
loudest = max(loudest, media.getSampleValue(sample))
return loudest
def normalize(sound):
new_sound = media.duplicateSound(sound)
largest = find_loudest(new_sound)
multiplier = 32767 / largest
print ("Largest sample value in original sound was",largest)
print ("Multiplier is", multiplier)
for sample in media.getSamples(new_sound):
louder = multiplier * media.getSampleValue(sample)
media.setSampleValue(sample,louder)
return new_sound
def clip(sound):
for sample in media.getSamples(new_sound):
if media.getSampleValue(sample) >= 0:
media.setSampleValue(sample, 32767)
else:
media.setSampleValue(sample, -32768)
return new_sound
audio = media.makeSound('sounds/thisisatest.wav')
media.explore(audio)
media.blockingPlay(audio)
louder_audio = change_volume(audio, 5)
media.explore(louder_audio)
media.blockingPlay(louder_audio)
print(media.getSampleValueAt(audio, 17741))
print(media.getSampleValueAt(louder_audio, 17741))
media.explore(audio)
media.blockingPlay(audio)
partially_louder_audio = change_volume_range(audio, 7, 46341, 57864)
media.explore(partially_louder_audio)
media.blockingPlay(partially_louder_audio)
print(media.getSampleValueAt(audio, 20000))
print(media.getSampleValueAt(partially_louder_audio, 20000))
print(media.getSampleValueAt(audio, 50000))
print(media.getSampleValueAt(partially_louder_audio, 50000))
normalized_audio = normalize(audio)
media.blockingPlay(audio)
media.blockingPlay(normalized_audio)
clipped = clip(audio)
media.explore(clipped)
media.blockingPlay(clipped)
media.quit()