]> Creatis software - CreaPhase.git/blob - octave_packages/m/audio/saveaudio.m
update packages
[CreaPhase.git] / octave_packages / m / audio / saveaudio.m
1 ## Copyright (C) 1995-2012 John W. Eaton
2 ##
3 ## This file is part of Octave.
4 ##
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
9 ##
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 ## General Public License for more details.
14 ##
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING.  If not, see
17 ## <http://www.gnu.org/licenses/>.
18
19 ## -*- texinfo -*-
20 ## @deftypefn {Function File} {} saveaudio (@var{name}, @var{x}, @var{ext}, @var{bps})
21 ## Save a vector @var{x} of audio data to the file
22 ## @file{@var{name}.@var{ext}}.  The optional parameters @var{ext} and
23 ## @var{bps} determine the encoding and the number of bits per sample used
24 ## in the audio file (see @code{loadaudio}); defaults are @file{lin} and
25 ## 8, respectively.
26 ## @seealso{lin2mu, mu2lin, loadaudio, playaudio, setaudio, record}
27 ## @end deftypefn
28
29 ## Author: AW <Andreas.Weingessel@ci.tuwien.ac.at>
30 ## Created: 5 September 1994
31 ## Adapted-By: jwe
32
33 function saveaudio (name, x, ext, bps)
34
35   if (nargin < 2 || nargin > 4)
36     print_usage ();
37   endif
38
39   if (nargin == 2)
40     ext = "lin";
41   endif
42
43   if (nargin < 4)
44     bps = 8;
45   elseif (bps != 8 && bps != 16)
46     error ("saveaudio: BPS must be either 8 or 16");
47   endif
48
49   [nr, nc] = size (x);
50   if (nc != 1)
51     if (nr == 1)
52       x = x';
53       nr = nc;
54     else
55       error ("saveaudio: X must be a vector");
56     endif
57   endif
58
59   num = fopen ([name, ".", ext], "wb");
60
61   if (strcmp (ext, "lin") || strcmp (ext, "raw"))
62     if (bps == 8)
63       ld = max (abs (x));
64       if (ld > 127)   # convert 16 to 8 bit
65         if (ld < 16384)
66           sc = 64 / ld;
67         else
68           sc = 1 / 256;
69         endif
70         x = fix (x * sc);
71       endif
72       x = x + 127;
73       c = fwrite (num, x, "uchar");
74     else
75       c = fwrite (num, x, "short");
76     endif
77   elseif (strcmp (ext, "mu") || strcmp (ext, "au")
78           || strcmp (ext, "snd") || strcmp (ext, "ul"))
79     y = lin2mu (x);
80     c = fwrite (num, y, "uchar");
81   else
82     fclose (num);
83     error ("saveaudio: unsupported extension");
84   endif
85
86   fclose (num);
87
88 endfunction