How can I make a siren noise in Python? - python

I'm trying to make a siren sound in python with beeps, but had no success..
I'm trying something like
winsound.Beep(700,500)
winsound.Beep(710,500)
winsound.Beep(720,500)
...
It's a better way to do it? And play it?
Without external files...
Thx

Record a high quality siren as a WAV file (Audacity is a nice tool for this task, and might even provide the right mix of sound generators for this) and use PlaySound.
winsound.PlaySound('siren.wav', winsound.SND_FILENAME)
You could also bundle it into the script as a string to avoid having a separate file:
siren = base64.b64decode('''
<base64-encoded data>
''')
winsound.PlaySound(siren, winsound.SND_MEMORY)
To create the data for siren, run the WAV file through a base64 encoder (e.g., here is a basic command-line tool — the download includes a win32 exe) and paste the output into the siren string. Base64 isn't a requirement, by the way; it's just a convenient way to embed binary data into a Python source file.

I remember using something similar on QBASIC when I was still a kid:
DO
FOR n = -180 TO 180 STEP .1
f = 440 + 50 * SIN(n)
SOUND f, 1
NEXT
LOOP
SOUND f, 1 should be the same thing as winsound.Beep, with pitch and duration. It used to work great but since I took the snippet here I'm not sure I did exactly this way.
It's just to give you the idea..

Related

python ringtone maker : how to split files

I'm writing an application for making ringtones for the iPhone. It's just for fun.
Here's what I've done till now. (Mind you, i'm a beginner in Python !)
So I open my mp3 file in binary mode. read the whole file. Convert it into a list. Use list slicing to split the file. Save this new split into a new mp3 file. This works fine. I however want to the ringtones to have a max of 30 seconds play time and I want the user to choose what portion of the file he wants as the ringtone. Can anyone guide me in the right direction ? Thanks
Here's my code till now :
f = open("Bruno Mars - Locked Out Of Heaven [OFFICIAL VIDEO].mp3", 'rb').read()
mp3 = list(f)
fo = open("newFile.mp3", "wb")
print(mp3[0:1300000])
fo.write(bytes(mp3[0:1300000]))
Here's what I got after some coding:
import os
f = open("Bruno Mars - Locked Out Of Heaven [OFFICIAL VIDEO].mp3", 'rb').read()
fileSize = os.path.getsize("Bruno Mars - Locked Out Of Heaven [OFFICIAL VIDEO].mp3")
print("Size of the whole file",fileSize)
mp3 = list(f)
bitRate = int(input("Enter the bit rate of your file"))
size_mbps = bitRate*(15/2048)
print("MB per minute :",size_mbps)
second_size = int((size_mbps/60)*(10**6))
print("Size of each second :",second_size)
start_length = int(input("Enter the start time (in seconds)"))
end_length = int(input("Enter the end time (in seconds)"))
start_size = int(second_size*start_length)
end_size = int(second_size*end_length)
fo = open("newFile.mp3", "wb")
fo.write(bytes(mp3[start_size:end_size]))
It works fine but I need to tweak it a little more. Any input on this code ?
If you want to use a higher-level language like c++ to implement a custom MP3 decoder, take a look a this question, time length of an mp3 file.
Otherwise, there are other libraries that do just what you need:
PyMad -
import mad
mf = mad.MadFile("foo.mp3")
track_length_in_milliseconds = mf.total_time()
audioread -
audio = audioread.audio_open('/path/to/mp3')
print f.channels, f.samplerate, f.duration
Mutagen -
from mutagen.mp3 import MP3
audio = MP3("example.mp3")
print audio.info.length
There are many more, but for now you can start with these.
You have to be a bit careful since mp3 frames do not always stand on their own, which is one of the reasons high end music tools will first convert to WAV or something like it, but as you remarked, it does work up till a certain level.
You could probably benefit from looking at the code in the following project (note that it is GPL licensed though):
http://sourceforge.net/projects/pymp3cut/
the interesting bits:
http://pymp3cut.cvs.sourceforge.net/viewvc/pymp3cut/pymp3cut/pmpcmp3.py?revision=1.2&view=markup
Once you extracted the actual music part, the rough idea is that you base yourself on the bitrate to get the relation between the framesize, seconds, filesize and byte content, which then tells you where to split the bytes to get the starting time and duration that you want.

Linux and python: Combining multiple wave files to one wave file

I am looking for a way that I can combine multiple wave files into one wave file using python and run it on linux. I don't want to use any add on other than the default shell command line and default python modules.
For example, if I have a.wav and b.wav. I want to create a c.wav which start with the content from a.wav then b.wav.
I've found wave module, that I can open a wave file and write into a new file. Since i'm really new in this audio world. I still can't figure out how to do it. Below is my code
import struct, wave
waveFileA = wave.open('./a.wav', 'r')
waveFileB = wave.open('./b.wav', 'r')
waveFileC = wave.open('./c.wav', 'w')
lengthA = waveFileA.getnframes()
for i in range(0,lengthA):
waveFileC.writeframes(waveFileA.readframes(1))
lengthB = waveFileB.getnframes()
for i in range(0,lengthB):
waveFileC.writeframes(waveFileB.readframes(1))
waveFileA.close()
waveFileB.close()
waveFileC.close()
When i run this code, I got this error:
wave.Error: # channels not specified
Please can any one help me?
You need to set the number of channels, sample width, and frame rate:
waveFileC.setnchannels(waveFileA.getnchannels())
waveFileC.setsampwidth(waveFileA.getsampwidth())
waveFileC.setframerate(waveFileA.getframerate())
If you want to handle a.wav and b.wav having different settings, you'll want to use something like pysox to convert them to the same settings, or for nchannels and sampwidth you may be able to tough through it yourself.
Looks like you need to call n=waveFileA.getnchannels() to find out how many channels the first input file uses, likewise for waveFileB, then you'll need to use waveFileC.setnchannels(n) to tell it how many channels to put in the outgoing file. I don't know how it will handle input files with different numbers of channels...
Here is the answer I am looking for
How to join two wav files using python?
(look for a thread by Tom 10)
It's in another thread. some one already solved this problem.

Simple questions about txt file input and output with Python 2.6

this is my first post here to stackoverflow, and I am still just learning Python and programming in general. I'm working on some simple game logic, and I'm getting a little washed up on how Python handles file input/output.
What I'm trying to do is, while my game is running, store a series of variables (all numeric, integer data), and when the game is over, dump that information to txt file that can later be read (again, as numeric, integer data) so that it can be added to. A tracker, really.
Perhaps if you were playing some racing game, for example, every time you hit a pedestrian, pedestrians += 1. Then when your game is over, after hitting like 23 pedestrians, that number (along with any other variables I wished to track) is saved to a text file. When you start the game again, it loads the number 23 back into the pedestrians variable, so if you hit 30 more this time you end up with 53 total, and so on. Thanks in advance!
Does it have to be text? I'd use pickle if not
http://docs.python.org/library/pickle.html
There are quite a few ways to do this. Do you want the file to be human-readable or human-writable? (Could encourage cheating if you do.)
The simplest thing that you could do which would work is to use the ConfigParser library, which stores simple data like what you described in a text file. Something like:
Reading:
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open('game_data.dat'))
dead_pedestrians = config.getint('JoeUser', 'dead_pedestrians')
Writing:
config = ConfigParser.RawConfigParser()
config.add_section('JoeUser')
config.set('JoeUser', 'dead_pedestrians', '15')
with open('game_data.dat', 'wb') as configfile:
config.write(configfile)
Other options: If you don't want it to be human-readable, you could use shelve (but a clever user who knows you're using python would find it trivial to read.
Hope that helps!

Python open raw audio data file

I have these files with the extension ".adc". They are simply raw data files. I can open them with Audacity using File->Import->Raw data with encoding "Signed 16 bit" and sample rate "16000 Khz".
I would like to do the same with python. I think that audioop module is what I need, but I can't seem to find examples on how to use it for something that simple.
The main goal is to open the file and play a certain location in the file, for example from the second 10 to the second 20. Is there something out there for my task ?
Thanx in advance.
For opening the file, you just need file().
For finding a location, you don't need audioop: you just need to convert seconds to bytes and get the required bytes of the file. For instance, if your file is 16 kHz 16bit mono, each second is 32,000 bytes of data. So the 10th second is 320kB into the file. Just seek to the appropriate place in the file and then read the appropriate number of bytes.
And audioop can't help you with the hardest part: namely, playing the audio. The correct way to do this very much depends on your OS.
EDIT: Sorry, I just noticed your username is "thelinuxer". Consider pyAO for playing audio from Python on Linux. You will probably need to change the sample format to play the audio---audioop will help you with this (see ratecv, tomono/tostereo, lin2lin, and bias)
Thanx a lot I was able to do the following:
def play_data(filename, first_sec, second_sec):
import ao
from ao import AudioDevice
dev = AudioDevice(2, bits=16, rate=16000,channels=1)
f = open(filename, 'r')
data_len = (second_sec-first_sec)*32000
f.seek(32000*first_sec)
data = f.read(data_len)
dev.play(data)
f.close()
play_data('AR001_3.adc', 2.5, 5)
You can use PySoundFile to open the file as a NumPy array and play it with python-sounddevice.
import soundfile as sf
import sounddevice as sd
sig, fs = sf.read('myfile.adc', channels=2, samplerate=16000,
format='RAW', subtype='PCM_16')
sd.play(sig, fs)
You can use indexing on the NumPy array to select a certain part of the audio data.

abstracting the conversion between id3 tags, m4a tags, flac tags

I'm looking for a resource in python or bash that will make it easy to take, for example, mp3 file X and m4a file Y and say "copy X's tags to Y".
Python's "mutagen" module is great for manupulating tags in general, but there's no abstract concept of "artist field" that spans different types of tag; I want a library that handles all the fiddly bits and knows fieldname equivalences. For things not all tag systems can express, I'm okay with information being lost or best-guessed.
(Use case: I encode lossless files to mp3, then go use the mp3s for listening. Every month or so, I want to be able to update the 'master' lossless files with whatever tag changes I've made to the mp3s. I'm tired of stubbing my toes on implementation differences among formats.)
I needed this exact thing, and I, too, realized quickly that mutagen is not a distant enough abstraction to do this kind of thing. Fortunately, the authors of mutagen needed it for their media player QuodLibet.
I had to dig through the QuodLibet source to find out how to use it, but once I understood it, I wrote a utility called sequitur which is intended to be a command line equivalent to ExFalso (QuodLibet's tagging component). It uses this abstraction mechanism and provides some added abstraction and functionality.
If you want to check out the source, here's a link to the latest tarball. The package is actually a set of three command line scripts and a module for interfacing with QL. If you want to install the whole thing, you can use:
easy_install QLCLI
One thing to keep in mind about exfalso/quodlibet (and consequently sequitur) is that they actually implement audio metadata properly, which means that all tags support multiple values (unless the file type prohibits it, which there aren't many that do). So, doing something like:
print qllib.AudioFile('foo.mp3')['artist']
Will not output a single string, but will output a list of strings like:
[u'The First Artist', u'The Second Artist']
The way you might use it to copy tags would be something like:
import os.path
import qllib # this is the module that comes with QLCLI
def update_tags(mp3_fn, flac_fn):
mp3 = qllib.AudioFile(mp3_fn)
flac = qllib.AudioFile(flac_fn)
# you can iterate over the tag names
# they will be the same for all file types
for tag_name in mp3:
flac[tag_name] = mp3[tag_name]
flac.write()
mp3_filenames = ['foo.mp3', 'bar.mp3', 'baz.mp3']
for mp3_fn in mp3_filenames:
flac_fn = os.path.splitext(mp3_fn)[0] + '.flac'
if os.path.getmtime(mp3_fn) != os.path.getmtime(flac_fn):
update_tags(mp3_fn, flac_fn)
I have a bash script that does exactly that, atwat-tagger. It supports flac, mp3, ogg and mp4 files.
usage: `atwat-tagger.sh inputfile.mp3 outputfile.ogg`
I know your project is already finished, but somebody who finds this page through a search engine might find it useful.
Here's some example code, a script that I wrote to copy tags between
files using Quod Libet's music format classes (not mutagen's!). To run
it, just do copytags.py src1 dest1 src2 dest2 src3 dest3, and it
will copy the tags in sec1 to dest1 (after deleting any existing tags
on dest1!), and so on. Note the blacklist, which you should tweak to
your own preference. The blacklist will not only prevent certain tags
from being copied, it will also prevent them from being clobbered in
the destination file.
To be clear, Quod Libet's format-agnostic tagging is not a feature of mutagen; it is implemented on top of mutagen. So if you want format-agnostic tagging, you need to use quodlibet.formats.MusicFile to open your files instead of mutagen.File.
Code can now be found here: https://github.com/DarwinAwardWinner/copytags
If you also want to do transcoding at the same time, use this: https://github.com/DarwinAwardWinner/transfercoder
One critical detail for me was that Quod Libet's music format classes
expect QL's configuration to be loaded, hence the config.init line in my
script. Without that, I get all sorts of errors when loading or saving
files.
I have tested this script for copying between flac, ogg, and mp3, with "standard" tags, as well as arbitrary tags. It has worked perfectly so far.
As for the reason that I didn't use QLLib, it didn't work for me. I suspect it was getting the same config-related errors as I was, but was silently ignoring them and simply failing to write tags.
You can just write a simple app with a mapping of each tag name in each format to an "abstract tag" type, and then its easy to convert from one to the other. You don't even have to know all available types - just those that you are interested in.
Seems to me like a weekend-project type of time investment, possibly less. Have fun, and I won't mind taking a peek at your implementation and even using it - if you won't mind releasing it of course :-) .
There's also tagpy, which seems to work well.
Since the other solutions have mostly fallen off the net, here is what I came up, based on the python mediafile library (python3-mediafile in Debian GNU/Linux).
#!/usr/bin/python3
import sys
from mediafile import MediaFile
src = MediaFile (sys.argv [1])
dst = MediaFile (sys.argv [2])
for field in src.fields ():
try:
setattr (dst, field, getattr (src, field))
except:
pass
dst.save ()
Usage: mediafile-mergetags srcfile dstfile
It copies (merges) all tags from srcfile into dstfile, and seems to work properly with flac, opus, mp3 and so on, including copying album art.

Categories

Resources