0

I am trying to write a program to determine the maximum value of a sample from a sound. The loop returns the values of all the samples, however I cannot figure out how to print the largest.

def largest():
f=pickAFile()
sound=makeSound(f)
for i in range(1,getLength(sound)):
  value=getSampleValueAt(sound,i)
print max([value])
1
  • Please fix your indentation. Commented Aug 28, 2014 at 14:21

3 Answers 3

3

Try:

def largest():
    f = pickAFile()
    sound = makeSound(f)
    value = []
    for i in range(1, getLength(sound)):
      value.append(getSampleValueAt(sound, i))
    print max(value)

Or

def largest():
    f = pickAFile()
    sound = makeSound(f)
    print max(getSampleValueAt(sound, i) for i in range(1, getLength(sound)))

With your code, value is overwritten at each iteration. If you make a list with all the values, you can then find the max using max.

Also see:

Sign up to request clarification or add additional context in comments.

2 Comments

This works, although I am also trying to count the occurrence of "0" in the sample now which is retrieving a thread death. Is value.count("0") a viable why to do it?
It should be, but isn't the values integers, so you would need value.count(0)?
1

Don't remember we are dealing with audio data. With possibly millions of samples. If you want to stick with something efficient both in space and time, you have to rely on the far less sexy:

def largest():
    f = pickAFile()
    sound = makeSound(f)
    max = getSampleValueAt(sound, 1) # FIX ME: exception (?) if no data
    idx = 2
    while idx < getLength(sound):
        v = getSampleValueAt(sound, i)
        if v > max:
            max = v
        i += 1

    print max

Generator-based solution are efficient too in term of space, but for speed, nothing could beat a plain-old imperative loop in Python.

Comments

0

Didn't test it but maybe:

def largest():
 f=pickAFile()
 sound=makeSound(f)
 value = [ getSampleValueAt(sound,i) for i in range(1,getLength(sound)) ]
 print max(value)

2 Comments

And what if you have several Msamples?
@Sylvain Leroux well then I would have to change it but this should be the fix to the code provided with the topic

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.