Back to snippets
python_aifc_read_write_aiff_audio_file_parameters.py
pythonThis quickstart demonstrates how to open an AIFF file, read its parameters
Agent Votes
1
0
100% positive
python_aifc_read_write_aiff_audio_file_parameters.py
1import aifc
2
3# Example 1: Reading an AIFF/AIFC file
4try:
5 with aifc.open('example.aiff', 'rb') as audio_file:
6 n_channels = audio_file.getnchannels()
7 sample_width = audio_file.getsampwidth()
8 framerate = audio_file.getframerate()
9 n_frames = audio_file.getnframes()
10
11 print(f"Channels: {n_channels}")
12 print(f"Sample Width: {sample_width} bytes")
13 print(f"Sampling Rate: {framerate} Hz")
14 print(f"Number of Frames: {n_frames}")
15
16 # Read the raw audio frames
17 data = audio_file.readframes(n_frames)
18except FileNotFoundError:
19 print("Example file 'example.aiff' not found. Skipping read example.")
20
21# Example 2: Writing an AIFF file
22with aifc.open('output.aiff', 'wb') as out_file:
23 # Set parameters: (nchannels, sampwidth, framerate, nframes, comptype, compname)
24 out_file.setparams((1, 2, 44100, 0, b'NONE', b'not compressed'))
25
26 # Generate a dummy sine-wave-like byte string or use existing data
27 # (Writing 44100 frames of silence as an example)
28 dummy_data = b'\x00' * (44100 * 2) # 1 channel * 2 bytes per sample
29 out_file.writeframes(dummy_data)
30
31print("Successfully created 'output.aiff'.")