Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Помогите разобраться AudioRecorder 
V
    Опции темы
IndigoStill
Дата 1.5.2008, 16:45 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 11
Регистрация: 21.10.2007

Репутация: нет
Всего: нет



Скачал исходник все нормально компилирует но ничего не делает  smile  выдает

 
Код

init:
deps-jar:
Compiling 1 source file to D:\1\JavaLibrary1\build\classes
compile-single:
run-single:
SimpleAudioRecorder: usage:
        java SimpleAudioRecorder -h
        java SimpleAudioRecorder <audiofile>
BUILD SUCCESSFUL (total time: 0 seconds)


Почему не начинается запись?
(Вот исходник с авторскими пометками.)

Код

import java.io.IOException;
import java.io.File;

import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.AudioFileFormat;



/**    <titleabbrev>SimpleAudioRecorder</titleabbrev>
    <title>Recording to an audio file (simple version)</title>

    <formalpara><title>Purpose</title>
    <para>Records audio data and stores it in a file. The data is
    recorded in CD quality (44.1 kHz, 16 bit linear, stereo) and
    stored in a <filename>.wav</filename> file.</para></formalpara>

    <formalpara><title>Usage</title>
    <para>
    <cmdsynopsis>
    <command>java SimpleAudioRecorder</command>
    <arg choice="plain"><option>-h</option></arg>
    </cmdsynopsis>
    <cmdsynopsis>
    <command>java SimpleAudioRecorder</command>
    <arg choice="plain"><replaceable>audiofile</replaceable></arg>
    </cmdsynopsis>
    </para></formalpara>

    <formalpara><title>Parameters</title>
    <variablelist>
    <varlistentry>
    <term><option>-h</option></term>
    <listitem><para>print usage information, then exit</para></listitem>
    </varlistentry>
    <varlistentry>
    <term><option><replaceable>audiofile</replaceable></option></term>
    <listitem><para>the file name of the
    audio file that should be produced from the recorded data</para></listitem>
    </varlistentry>
    </variablelist>
    </formalpara>

    <formalpara><title>Bugs, limitations</title>
    <para>
    You cannot select audio formats and the audio file type
    on the command line. See
    AudioRecorder for a version that has more advanced options.
    Due to a bug in the Sun jdk1.3/1.4, this program does not work
    with it.
    </para></formalpara>

    <formalpara><title>Source code</title>
    <para>
    <ulink url="SimpleAudioRecorder.java.html">SimpleAudioRecorder.java</ulink>
    </para>
    </formalpara>

*/
public class SimpleAudioRecorder
extends Thread
{
    private TargetDataLine        m_line;
    private AudioFileFormat.Type    m_targetType;
    private AudioInputStream    m_audioInputStream;
    private File            m_outputFile;



    public SimpleAudioRecorder(TargetDataLine line,
                     AudioFileFormat.Type targetType,
                     File file)
    {
        m_line = line;
        m_audioInputStream = new AudioInputStream(line);
        m_targetType = targetType;
        m_outputFile = file;
    }



    /** Starts the recording.
        To accomplish this, (i) the line is started and (ii) the
        thread is started.
    */
    public void start()
    {
        /* Starting the TargetDataLine. It tells the line that
           we now want to read data from it. If this method
           isn't called, we won't
           be able to read data from the line at all.
        */
        m_line.start();

        /* Starting the thread. This call results in the
           method 'run()' (see below) being called. There, the
           data is actually read from the line.
        */
        super.start();
    }


    /** Stops the recording.

        Note that stopping the thread explicitely is not necessary. Once
        no more data can be read from the TargetDataLine, no more data
        be read from our AudioInputStream. And if there is no more
        data from the AudioInputStream, the method 'AudioSystem.write()'
        (called in 'run()' returns. Returning from 'AudioSystem.write()'
        is followed by returning from 'run()', and thus, the thread
        is terminated automatically.

        It's not a good idea to call this method just 'stop()'
        because stop() is a (deprecated) method of the class 'Thread'.
        And we don't want to override this method.
    */
    public void stopRecording()
    {
        m_line.stop();
        m_line.close();
    }




    /** Main working method.
        You may be surprised that here, just 'AudioSystem.write()' is
        called. But internally, it works like this: AudioSystem.write()
        contains a loop that is trying to read from the passed
        AudioInputStream. Since we have a special AudioInputStream
        that gets its data from a TargetDataLine, reading from the
        AudioInputStream leads to reading from the TargetDataLine. The
        data read this way is then written to the passed File. Before
        writing of audio data starts, a header is written according
        to the desired audio file type. Reading continues untill no
        more data can be read from the AudioInputStream. In our case,
        this happens if no more data can be read from the TargetDataLine.
        This, in turn, happens if the TargetDataLine is stopped or closed
        (which implies stopping). (Also see the comment above.) Then,
        the file is closed and 'AudioSystem.write()' returns.
    */
    public void run()
    {
            try
            {
                AudioSystem.write(
                    m_audioInputStream,
                    m_targetType,
                    m_outputFile);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
    }



    public static void main(String[] args)
    {
                    if (args.length != 1 || args[0].equals("-h"))
        {
            printUsageAndExit();
        }

        /* We have made shure that there is only one command line
           argument. This is taken as the filename of the soundfile
           to store to.
        */
        String    strFilename = args[0];
        File    outputFile = new File(strFilename);

        /* For simplicity, the audio data format used for recording
           is hardcoded here. We use PCM 44.1 kHz, 16 bit signed,
           stereo.
        */
        AudioFormat    audioFormat = new AudioFormat(
            AudioFormat.Encoding.PCM_SIGNED,
            44100.0F, 16, 2, 4, 44100.0F, false);

        /* Now, we are trying to get a TargetDataLine. The
           TargetDataLine is used later to read audio data from it.
           If requesting the line was successful, we are opening
           it (important!).
        */
        DataLine.Info    info = new DataLine.Info(TargetDataLine.class, audioFormat);
        TargetDataLine    targetDataLine = null;
        try
        {
            targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
            targetDataLine.open(audioFormat);
        }
        catch (LineUnavailableException e)
        {
            out("unable to get a recording line");
            e.printStackTrace();
            System.exit(1);
        }

        /* Again for simplicity, we've hardcoded the audio file
           type, too.
        */
        AudioFileFormat.Type    targetType = AudioFileFormat.Type.WAVE;

        /* Now, we are creating an SimpleAudioRecorder object. It
           contains the logic of starting and stopping the
           recording, reading audio data from the TargetDataLine
           and writing the data to a file.
        */
        SimpleAudioRecorder    recorder = new SimpleAudioRecorder(
            targetDataLine,
            targetType,
            outputFile);

        /* We are waiting for the user to press ENTER to
           start the recording. (You might find it
           inconvenient if recording starts immediately.)
        */
        out("Press ENTER to start the recording.");
        try
        {
            System.in.read();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        /* Here, the recording is actually started.
         */
        recorder.start();
        out("Recording...");

        /* And now, we are waiting again for the user to press ENTER,
           this time to signal that the recording should be stopped.
        */
        out("Press ENTER to stop the recording.");
        try
        {
            System.in.read();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        /* Here, the recording is actually stopped.
         */
        recorder.stopRecording();
        out("Recording stopped.");
    }



    private static void printUsageAndExit()
    {
        out("SimpleAudioRecorder: usage:");
        out("\tjava SimpleAudioRecorder -h");
        out("\tjava SimpleAudioRecorder <audiofile>");
        System.exit(0);
    }



    private static void out(String strMessage)
    {
        System.out.println(strMessage);
    }
}



PM MAIL   Вверх
talaat
Дата 4.5.2008, 15:15 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 3
Регистрация: 29.12.2007

Репутация: нет
Всего: нет



Цитата

SimpleAudioRecorder: usage:
        java SimpleAudioRecorder -h
        java SimpleAudioRecorder <audiofile>

вот он тебе и показывает что если хочешь помошь то запускаешь
java SimpleAudioRecorder -h

если записывать то 
java SimpleAudioRecorder <audiofile>

тебе просто надо передавать параметр который будет файлом в который и произойдет запись.
PM MAIL   Вверх
IndigoStill
Дата 5.5.2008, 20:24 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 11
Регистрация: 21.10.2007

Репутация: нет
Всего: нет



В томто и вопрос я не знаю (не панемаю) как передать параметр.
PM MAIL   Вверх
LSD
Дата 6.5.2008, 13:01 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Leprechaun Software Developer
****


Профиль
Группа: Модератор
Сообщений: 15718
Регистрация: 24.3.2004
Где: Dublin

Репутация: 210
Всего: 538



Цитата(IndigoStill @  5.5.2008,  21:24 Найти цитируемый пост)
В томто и вопрос я не знаю (не панемаю) как передать параметр.

Внимательно перечитай пост talaat smile 
(перечитывать до тех пор пока не поможет)


--------------------
Disclaimer: this post contains explicit depictions of personal opinion. So, if it sounds sarcastic, don't take it seriously. If it sounds dangerous, do not try this at home or at all. And if it offends you, just don't read it.
PM MAIL WWW   Вверх
talaat
Дата 6.5.2008, 16:18 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 3
Регистрация: 29.12.2007

Репутация: нет
Всего: нет



открываешь консоль где лежит скомпилированный java класс и пишешь
java SimpleAudioRecorder aaa.wav

и что программа делает будет записываться в файл aaa.wav

Я как понял ты пользуешься NetBeans
Там заходишь в Properties проекта, там выбираешь Run и в поле Arguments пишешь то что хочешь передать,
в данном случае это aaa.wav
PM MAIL   Вверх
IndigoStill
Дата 12.5.2008, 19:19 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 11
Регистрация: 21.10.2007

Репутация: нет
Всего: нет



Спасибо.
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic.

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0760 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.