精华内容
下载资源
问答
  • 录制音频

    千次阅读 2013-11-02 21:01:16
    想要在ios设备上录制音频,可以使用AVAudioRecorder类,确保你已经将CoreAudio.framework

    想要在ios设备上录制音频,可以使用AVAudioRecorder类,确保你已经将CoreAudio.framework 库添加到目标文件中

    AV框架中的AVAudioRecorder类使得在iOS中录制音频变得很简单。开始录制音频需要提供一些参数给AVAudioRecorder实例的initWithURL:settings:error:方法: 

    保存录音文件的URL 

    文件的URL是一个本地URL.AV框架会根据URL的扩展名来决定录制文件的音频格式。所以要仔细选择扩展名。 

    在采样之前和过程中使用的settings 

    包括采样率、频道以及其他音频录制器开始录音的信息。Setting是一个dictionary对象。 

    初始化错误发生时保存到error 变量中。 

    你可以在出现异常的情况下得到这个实例中的值。 

    initWithURL:settings:error: 方法的setting参数很有意思。很多值都可以保存在这个setting字典里,但是在本节中我们只讨论一些最重要的: 

    AVFormatIDKey 

    录音的格式。可能的值有: 

    kAudioFormatLinearPCM 

    kAudioFormatAppleLossless 

    AVSampleRateKey 

    录制音频的采样率。 

    AVNumberOfChannelsKey 

    录制音频的频道编号。 

    AVEncoderAudioQualityKey 

    录制音频的质量,可能的值有: 

    AVAudioQualityMin 

    AVAudioQualityLow 

    AVAudioQualityMedium 

    AVAudioQualityHigh 

    AVAudioQualityMax 

    掌握了所有这些信息后,我们可以开始写一个可以录制音频文件然后用AVAudioPlayer播放的程序。我们要做的具体事情是: 

    1. Apple Lossless 格式录制音频。 

    2. 把录制的音频文件用Recording.m4a文件名保存到程序的Documents目录中。 

    3. 在录音开始10秒后停止录制并且立刻开始播放录制的音频。 

    代码:

    头文件:

    #import <UIKit/UIKit.h>
    #import <CoreAudio/CoreAudioTypes.h>
    #import <AVFoundation/AVFoundation.h>
    
    @interface ViewController : UIViewController<AVAudioPlayerDelegate,AVAudioRecorderDelegate>
    @property(nonatomic, strong)AVAudioRecorder *audioRecorder;
    @property(nonatomic, strong)AVAudioPlayer *audioPlayer;
    -(NSString *)audioRecordingPath;
    -(NSString *)audioRecordingSettings;
    @end

    实现文件:

    //
    //  ViewController.m
    //  录制音频
    //
    //  Created by Rio.King on 13-11-2.
    //  Copyright (c) 2013年 Rio.King. All rights reserved.
    //
    
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    	
        NSError *error = nil;
        NSString *pathAsString = [self audioRecordingPath];
        NSURL *audioRecordingURL = [NSURL fileURLWithPath:pathAsString];
        self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:audioRecordingURL settings:[self audioRecordingSettings] error:&error];
        if (self.audioRecorder != nil) {
            self.audioRecorder.delegate = self;
            /*prepare the recorder and then start the recording*/
            if ([self.audioRecorder prepareToRecord] && [self.audioRecorder record]) {
                NSLog(@"Successfully started to record.");
                /*after five seconds, let's stop the recording process*/
                [self performSelector:@selector(stopRecordingOnAudioRecorder:) withObject:self.audioRecorder afterDelay:10.0f];
            }else{
                NSLog(@"Failed to record.");
                self.audioRecorder = nil;
            }
        }else{
            NSLog(@"failed to create an instance of the audio recorder.");
        }
    }
    
    -(NSString *)audioRecordingPath{
        NSString *result = nil;
        NSArray *folders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsFolder = [folders objectAtIndex:0];
        result = [documentsFolder stringByAppendingPathComponent:@"Recording.m4a"];
        return result;
    }
    
    - (NSDictionary *) audioRecordingSettings{
        NSDictionary *result = nil;
        /* Let's prepare the audio recorder options in the dictionary.
         Later we will use this dictionary to instantiate an audio
         recorder of type AVAudioRecorder */
        NSMutableDictionary *settings = [[NSMutableDictionary alloc] init];
        [settings
         setValue:[NSNumber numberWithInteger:kAudioFormatAppleLossless]
         forKey:AVFormatIDKey];
        [settings
         setValue:[NSNumber numberWithFloat:44100.0f]
         forKey:AVSampleRateKey];
        [settings
         setValue:[NSNumber numberWithInteger:1]
         forKey:AVNumberOfChannelsKey];
        [settings
         setValue:[NSNumber numberWithInteger:AVAudioQualityLow]
         forKey:AVEncoderAudioQualityKey];
        result = [NSDictionary dictionaryWithDictionary:settings];
        return result;
    }
    
    
    - (void) stopRecordingOnAudioRecorder:(AVAudioRecorder *)paramRecorder{
        /* Just stop the audio recorder here */
        [paramRecorder stop];
    }
    
    
    - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder
                               successfully:(BOOL)flag{
        if (flag){
            NSLog(@"Successfully stopped the audio recording process.");
            /* Let's try to retrieve the data for the recorded file */
            NSError *playbackError = nil;
            NSError *readingError = nil;
            NSData *fileData =
            [NSData dataWithContentsOfFile:[self audioRecordingPath]
                                   options:NSDataReadingMapped
                                     error:&readingError];
            /* Form an audio player and make it play the recorded data */
            self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData
                                                             error:&playbackError];
            /* Could we instantiate the audio player? */
            if (self.audioPlayer != nil){
                self.audioPlayer.delegate = self;
                /* Prepare to play and start playing */
                if ([self.audioPlayer prepareToPlay] &&
                    [self.audioPlayer play]){
                    NSLog(@"Started playing the recorded audio.");
                } else {
                    NSLog(@"Could not play the audio.");
                }
            } else {
                NSLog(@"Failed to create an audio player.");
            }
        } else {
            NSLog(@"Stopping the audio recording failed.");
        }
        /* Here we don't need the audio recorder anymore */
        self.audioRecorder = nil;
    }
    
    - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
                           successfully:(BOOL)flag{
        if (flag){
            NSLog(@"Audio player stopped correctly.");
        } else {
            NSLog(@"Audio player did not stop correctly.");
        }
        if ([player isEqual:self.audioPlayer]){
            self.audioPlayer = nil;
        } else {
            /* This is not the player */
        }
    }
    
    
    - (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
        /* The audio session has been deactivated here */
    }
    - (void)audioPlayerEndInterruption:(AVAudioPlayer *)player
                             withFlags:(NSUInteger)flags{
        if (flags == AVAudioSessionInterruptionFlags_ShouldResume){
            [player play];
        }
    }
    
    
    
    #pragma mark -处理音频录制过程中的中断
    - (void)audioRecorderBeginInterruption:(AVAudioRecorder *)recorder{
        NSLog(@"Recording process is interrupted");
    }
    - (void)audioRecorderEndInterruption:(AVAudioRecorder *)recorder
                               withFlags:(NSUInteger)flags{
        if (flags == AVAudioSessionInterruptionFlags_ShouldResume){
            NSLog(@"Resuming the recording...");
            [recorder record];
        }
    }
    
    
    
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    @end
    

    运行结果:

    2013-11-02 21:01:52.144 录制音频[1786:a0b] Successfully started to record.

    2013-11-02 21:02:02.146 录制音频[1786:a0b] Successfully stopped the audio recording process.

    2013-11-02 21:02:02.160 录制音频[1786:a0b] Started playing the recorded audio.

    2013-11-02 21:02:12.128 录制音频[1786:a0b] Audio player stopped correctly.



    展开全文
  • IOS录制音频

    2013-04-02 21:03:24
    IOS录制音频
  • 录制音频源代码

    2019-02-03 13:24:24
    录制音频源代码,用android studio写的,测试用的,主要功能为用audio record录制并生成wav文件,用media record录制生成amr文件,并通过socket发送生成的wav文件,亲测可用。
  • react 录制音频In this tutorial, we are going to learn how to record and play audio to React Native apps. We are going to build a simple screen that supports features such as recording audio, playing ...

    react 录制音频

    In this tutorial, we are going to learn how to record and play audio to React Native apps. We are going to build a simple screen that supports features such as recording audio, playing audio files, pausing and resuming, as well as resetting audio streams. The final app will look like the image below.

    在本教程中,我们将学习如何录制和播放音频到React Native应用程序。 我们将构建一个简单的屏幕,该屏幕支持录制音频,播放音频文件,暂停和恢复以及重置音频流等功能。 最终的应用程序将如下图所示。

    Originally published at https://www.instamobile.io on August 20, 2020.

    最初于 2020年8月20日 https://www.instamobile.io 发布

    Recording and playing audio in mobile applications is a very popular feature. Fortunately, to record and play audio in React Native apps can be done easily. This is thanks to the Expo ecosystem that easily supports sound recording in React Native. However, if we need to add any feature that requires us to migrate off the Expo system to React Native CLI, we may need to put much more effort into its configuration.

    在移动应用程序中录制和播放音频是非常受欢迎的功能。 幸运的是,在React Native应用程序中录制和播放音频可以轻松完成。 这要归功于Expo生态系统,该生态系统轻松支持React Native中的录音。 但是,如果我们需要添加任何需要从Expo系统迁移到React Native CLI的功能,则可能需要在其配置上付出更多的努力。

    As a result, we may need to use a third-party package. After much research, I have come up with a package that meets our requirements for recording and playing audio in React Native. The package name is react-native-audio-recorder-player. The package is easy to configure and provides us with robust modules and components to implement an audio recorder and player in React Native applications.

    因此,我们可能需要使用第三方程序包。 经过大量研究,我提出了一个满足我们在React Native中录制和播放音频的要求的软件包。 软件包名称是react-native-audio-recorder-player 。 该软件包易于配置,并为我们提供了强大的模块和组件,以在React Native应用程序中实现音频记录器和播放器。

    Without further ado, let’s get started!

    事不宜迟,让我们开始吧!

    先决条件 (Prerequisites)

    In order to go through this tutorial, we need to first prepare our React Native development environment. For this, we can easily follow other tutorials on Instamobile such as the one describing how to set up your React Native development environment.

    为了完成本教程,我们需要首先准备我们的React Native开发环境。 为此,我们可以轻松地遵循有关Instamobile的其他教程,例如描述如何设置React Native开发环境的教程。

    安装和设置软件包 (Installing and Setting Up the Package)

    First, we need to install the react-native-audio-recorder-player package using yarn or npm. I prefer using yarn so I am going to use yarn and run the following command in the project Terminal:

    首先,我们需要使用yarnnpm安装react-native-audio-recorder-player软件包。 我更喜欢使用yarn,所以我将使用yarn并在项目Terminal中运行以下命令:

    yarn add react-native-audio-recorder-player

    Then, we need to run the following command in order to run the app in the iOS device or simulator (simply replace ios with android if you are running on Android)

    然后,我们需要运行以下命令,以便在iOS设备或模拟器中运行该应用程序(如果您在Android上运行,只需将ios替换为android )

    react-native run-ios

    准备记录器组件 (Preparing the Recorder Component)

    Here, we start by importing the necessary methods from the react-native-audio-recorder-player package as shown in the code snippet below:

    在这里,我们首先从react-native-audio-recorder-player包中导入必要的方法,如下面的代码片段所示:

    import AudioRecorderPlayer, { 
    AVEncoderAudioQualityIOSType,
    AVEncodingOption,
    AudioEncoderAndroidType,
    AudioSet,
    AudioSourceAndroidType,
    } from 'react-native-audio-recorder-player';

    Then, we need to create a few new states and also initialize a new recorder instance as depicted in the code snippet below:

    然后,我们需要创建一些新状态,并初始化一个新的记录器实例,如下面的代码片段所示:

    class App extends Component {
    constructor(props) {
    super(props);
    this.state = {
    isLoggingIn: false,
    recordSecs: 0,
    recordTime: '00:00:00',
    currentPositionSec: 0,
    currentDurationSec: 0,
    playTime: '00:00:00',
    duration: '00:00:00',
    };
    this.audioRecorderPlayer = new AudioRecorderPlayer();
    this.audioRecorderPlayer.setSubscriptionDuration(0.09); // optional. Default is 0.1
    }

    准备UI (Preparing the UI)

    For the UI implementation, we are going to use components of the react-native-paper package. We already have an idea of how an audio player and recorder should look like. Hence, we can easily implement it on our screen. For a simple UI layout for the app, we can use the code from the following code snippet:

    对于UI实现,我们将使用react-native-paper包的组件。 我们已经对音频播放器和录音机的外观有所了解。 因此,我们可以轻松地在屏幕上实现它。 对于应用程序的简单UI布局,我们可以使用以下代码段中的代码:

    return (
    <Card style={{ flex: 1, flexDirection: 'row', alignItems: 'center', alignContent: 'center', alignSelf: 'center' }}>
    <Background>
    <Logo />
    <Header>InstaPlayer</Header>
    <Title>{this.state.recordTime}</Title>
    <Button mode="contained" icon="record" onPress={() => this.onStartRecord()}>
    RECORD
    </Button>
    <Button
    icon="stop"
    mode="outlined"
    onPress={() => this.onStopRecord()}
    >
    STOP
    </Button>
    <Divider />
    <Title>{this.state.playTime} / {this.state.duration}</Title>
    <Button mode="contained" icon="play" onPress={() => this.onStartPlay()}>
    PLAY
    </Button>
    <Button
    icon="pause"
    mode="contained"
    onPress={() => this.onPausePlay()}
    >
    PAUSE
    </Button>
    <Button
    icon="stop"
    mode="outlined"
    onPress={() => this.onStopPlay()}
    >
    STOP
    </Button>
    </Background>
    </Card>
    )

    Hence, we will get an audio recorder and an audio player on the same screen as displayed in the simulator screenshot below:

    因此,我们将在与下面的模拟器屏幕快照相同的屏幕上获得一个录音机和一个音频播放器:

    Image for post

    Now, it is time to implement the functions for each button on the screen.

    现在,是时候实现屏幕上每个按钮的功能了。

    在React Native中录制音频 (Record Audio in React Native)

    The first thing we need to do in any recording app is to implement the recording feature. The actual implementation is fairly simple for this. We need to follow these simple steps:

    在任何录制应用中,我们要做的第一件事就是实现录制功能。 实际的实现对此非常简单。 我们需要遵循以下简单步骤:

    1. Firstly, we start by defining an audio file name and extension.

      首先,我们从定义音频文件名和扩展名开始。
    2. Secondly, we define the audio format preference.

      其次,我们定义音频格式首选项。
    3. Lastly, we start to record audio and add a record time to the state.

      最后,我们开始记录音频并为该状态添加记录时间。

    The implementation for this is provided in the code snippet below:

    下面的代码段提供了此实现:

    onStartRecord = async () => {

    const path = 'hello.m4a';
    const audioSet = {
    AudioEncoderAndroid: AudioEncoderAndroidType.AAC,
    AudioSourceAndroid: AudioSourceAndroidType.MIC,
    AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,
    AVNumberOfChannelsKeyIOS: 2,
    AVFormatIDKeyIOS: AVEncodingOption.aac,
    };
    console.log('audioSet', audioSet);
    const uri = await this.audioRecorderPlayer.startRecorder(path, audioSet);
    this.audioRecorderPlayer.addRecordBackListener((e) => {
    this.setState({
    recordSecs: e.current_position,
    recordTime: this.audioRecorderPlayer.mmssss(
    Math.floor(e.current_position),
    ),
    });
    });
    console.log(`uri: ${uri}`);
    };

    Hence, we will get the result as shown in the demo screenshot of the emulator below (simply press the Record button):

    因此,我们将获得下面的仿真器的演示屏幕截图中所示的结果(只需按“ 记录”按钮):

    Image for post

    Here, we can see that the timer starts as we tap on the RECORD button.

    在这里,我们可以看到定时器在点击“ 记录”按钮时启动。

    停止录音 (Stopping Audio Recording)

    The stop recording feature is easy to implement as well. We just need to call the stopRecorder method and reset the time counter back to zero using the code from the following code snippet:

    停止记录功能也易于实现。 我们只需要调用stopRecorder方法,并使用以下代码片段中的代码将时间计数器重置为零即可:

    onStopRecord = async () => {
    const result = await this.audioRecorderPlayer.stopRecorder();
    this.audioRecorderPlayer.removeRecordBackListener();
    this.setState({
    recordSecs: 0,
    });
    console.log(result);
    };

    As you can notice we get the result as shown in the demo screenshot below:

    如您所见,我们得到的结果如下面的演示屏幕截图所示:

    Image for post

    Hence, the timer stops as we tap on the STOP button.

    因此,当我们点击“停止”按钮时,计时器停止。

    音频播放器以在React Native中播放音频 (Audio Player to Play Audio in React Native)

    Since we are done with the recording and stop recording features, we now have an audio file to play. In order to implement the play feature, we need to call the startPlayer method and pass the path to the file that we've just recorded. Then, we need to set the volume. Once the audio plays, we need to set a callback function to stop playing when the play counter indicator reaches the completion point. We also need to add current playtime to the state to display the counter properly in the UI. The implementation for this is provided in the code snippet below:

    由于我们已经完成了录制和停止录制功能,因此现在可以播放音频文件。 为了实现播放功能,我们需要调用startPlayer方法并将路径传递到我们刚刚记录的文件。 然后,我们需要设置音量。 音频播放后,我们需要设置一个回调函数,以在播放计数器指示器达到完成点时停止播放。 我们还需要将当前播放时间添加到状态中,以在UI中正确显示计数器。 下面的代码段提供了此实现:

    onStartPlay = async (e) => {
    console.log('onStartPlay');
    const path = 'hello.m4a'
    const msg = await this.audioRecorderPlayer.startPlayer(path);
    this.audioRecorderPlayer.setVolume(1.0);
    console.log(msg);
    this.audioRecorderPlayer.addPlayBackListener((e) => {
    if (e.current_position === e.duration) {
    console.log('finished');
    this.audioRecorderPlayer.stopPlayer();
    }
    this.setState({
    currentPositionSec: e.current_position,
    currentDurationSec: e.duration,
    playTime: this.audioRecorderPlayer.mmssss(
    Math.floor(e.current_position),
    ),
    duration: this.audioRecorderPlayer.mmssss(Math.floor(e.duration)),
    });
    });
    };

    Hence, we will get the result as shown in the demo screenshot below:

    因此,我们将获得如下演示屏幕快照中所示的结果:

    Image for post

    As you can see, when we tap the PLAY button, the audio starts playing.

    如您所见,当我们点击“播放”按钮时,音频开始播放。

    暂停音频播放器 (Pausing The Audio Player)

    Implementing a pause feature is simple. We just need to call the pausePlayer method, when PAUSE button is pressed. We can do this by using the following piece of code:

    实现暂停功能很简单。 当按下PAUSE按钮时,我们只需要调用pausePlayer方法。 我们可以使用下面的代码来做到这一点:

    onPausePlay = async (e) => { 
    await this.audioRecorderPlayer.pausePlayer();
    };

    Hence, we will get the result as shown in the demo screenshot below:

    因此,我们将获得如下演示屏幕快照中所示的结果:

    Image for post

    Here, we can see that when we hit the PAUSE button the player pauses, and when we hit the Play button again it starts to play from the same point where we stopped it.

    在这里,我们可以看到,当我们按下“暂停”按钮时,播放器会暂停,而当我们再次按下“播放”按钮时,它将从停止它的同一点开始播放。

    在React Native中停止音频播放器 (Stopping the Audio Player in React Native)

    In order to stop the player, we need to call the stopPlayer method. Then, we need to remove the playback data by calling removePlayBackListener method and reset the counter to zero again. The feature to trigger the stop action is provided as a function in the code snippet below:

    为了停止播放器,我们需要调用stopPlayer方法。 然后,我们需要通过调用removePlayBackListener方法删除播放数据,并将计数器再次重置为零。 下面的代码段中提供了触发停止操作的功能:

    onStopPlay = async (e) => {
    console.log('onStopPlay');
    this.audioRecorderPlayer.stopPlayer();
    this.audioRecorderPlayer.removePlayBackListener();
    };

    Hence, we will get the result as shown in the screenshot below:

    因此,我们将得到如下屏幕截图所示的结果:

    Image for post

    Here, we can see that when we hit the STOP button the player stops and after hitting the PLAY button, the counter starts from this beginning.

    在这里,我们可以看到,当我们按下STOP按钮时,播放器停止了,并且在按下PLAY按钮后,计数器从此开始。

    Finally, we have successfully implemented the audio recorder and player in the React Native application along with an intuitive UI layout. Hopefully now you know how to record audio in React Native and how to play the recorded audio files into a React Native audio player.

    最后,我们已经在React Native应用程序中成功实现了录音机和播放器以及直观的UI布局。 希望现在您知道如何在React Native中录制音频,以及如何将录制的音频文件播放到React Native音频播放器中。

    结论 (Conclusion)

    It has been an interesting feature to get our hands-on. Implementing an audio recorder and player in a React Native may sound difficult but in fact, it’s fairly simple thanks to a powerful library. This tutorial provides detailed guidance on each step so that it becomes even simpler. The package that we used for recording and playing audio is pretty robust and easy to implement as well. Make sure to get your hands dirty with it.

    动手操作是一个有趣的功能。 在React Native中实现录音机和播放器听起来很困难,但实际上,由于功能强大的库,这相当简单。 本教程为每个步骤提供了详细的指导,使其变得更加简单。 我们用于录制和播放音频的程序包非常健壮,并且易于实现。 确保将其弄脏。

    We can do tons of things in React Native utilizing this feature (think Spotify clone or Podcasts clone app). At Instamobile, we are using audio recording and playing in all of the apps that have a chat feature, such as our chat app template.

    我们可以利用此功能在React Native中做很多事情(想想Spotify克隆或Podcasts克隆应用程序)。 在Instamobile,我们正在所有具有聊天功能的应用程序(例如我们的聊天应用程序模板)中使用音频记录和播放。

    普通英语JavaScript (JavaScript In Plain English)

    Did you know that we have three publications and a YouTube channel? Find links to everything at plainenglish.io!

    您知道我们有三个出版物和一个YouTube频道吗? 在plainenglish.io上找到所有内容的链接!

    翻译自: https://medium.com/javascript-in-plain-english/how-to-record-audio-in-react-native-2d728bc6cc29

    react 录制音频

    展开全文
  • QT 录制音频

    千次阅读 2019-05-10 11:28:45
    主要是在创建QT项目的时候加入 multimedia库,利用这个库用来录制音频的。 QAudioFormat 这个类是用来设置录制音频的参数的,如下: QAudioFormat fmt; fmt.setSampleRate(sampleRate);// ...

    音频的推流和封装与视频是类似的,主要在于录制和重采样部分。

    QT再window的安装可以参考博客: vs2017 配置QT环境

    主要是在创建QT项目的时候加入 multimedia库,利用这个库用来录制音频的。

    QAudioFormat

    这个类是用来设置录制音频的参数的,如下:

    QAudioFormat fmt;
    	fmt.setSampleRate(sampleRate);// 采样率, 一秒采集音频样本数量,常设置为44100
    	fmt.setChannelCount(channels);  // 音频通道数
    	fmt.setSampleSize(16); //一个音频数据大小
    	fmt.setCodec("audio/pcm"); //编码方式,大多声卡只支持pcm,也可以通过获取参数得到声卡支持参数
    	fmt.setByteOrder(QAudioFormat::LittleEndian); // 小端 存储还是大端存储
    	fmt.setSampleType(QAudioFormat::UnSignedInt); // 数据类型,对应的是16位

    下图位大端存储和小端存储区别

    QAudioDeviceInfo

    音频设备信息,通产用来判断是否有音频设备。

    QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
    	if (!info.isFormatSupported(fmt))// 判断是否支持配置
    	{
    		cout << "Audio format not support!" << endl;
    		fmt = info.nearestFormat(fmt);// 如果不支持,取最近的配置方法。
    	}

    QAudioInput

    QT自带的音频输入类,将上面设置的格式信息给它,完成音频输入设备初始化。

    QAudioInput *input = new QAudioInput(fmt);
    
    //开始录制音频
    QIODevice *io = input->start();
    
    
    //一次读取一帧音频 input->bytesReady() 表示是准备好了多少数据(不是很准确)
    if (input->bytesReady() < readSize)
    {
    	QThread::msleep(1);
    	continue;
    }

    QIODevice 

    输入QAudioInput 开始录音后返回的device,根据device来读取数据到 buffer

    while (size != readSize)
    		{
    			int len = io->read(buf + size, readSize - size);
    			if (len < 0)break;
    			size += len;
    		}

    完整demo实现了录制音频和rtmp推流操作。

    展开全文
  • MediaRecorder录制音频

    2016-07-21 08:57:52
    MediaRecorder之录制音频


    为了保证录制时只有一个录音机,采取单例模式。


    public class AudioManager {
    
        private MediaRecorder mediaRecorder;
    
        private String mDir;
        private String mCurrentFilePath;
    
        private boolean isPrepare = false;
    
        private static AudioManager mAudioManager;
    
        public interface OnMediaRecorderPrepared{void prepared();}
        private OnMediaRecorderPrepared onMediaRecorderPrepared;
    
        private AudioManager(String dir){
            this.mDir = dir;
        };
    
        public void setOnMediaRecorderPrepared(OnMediaRecorderPrepared onMediaRecorderPrepared){
            this.onMediaRecorderPrepared = onMediaRecorderPrepared;
        }
    
        public static AudioManager getInstance(String dir){
            if(mAudioManager == null){
                synchronized (AudioManager.class){
                    if(mAudioManager == null){
                        mAudioManager = new AudioManager(dir);
                    }
                }
            }
            return mAudioManager;
        }
    
        public void prepare(){
            isPrepare = false;
            File dir = new File(mDir);
            if(!dir.exists()){
                dir.mkdir();
            }
    
            String fileName = generateFile();
            File file = new File(dir,fileName);
            mCurrentFilePath = file.getAbsolutePath();
            mediaRecorder = new MediaRecorder();
    <span style="white-space:pre">	</span>//设置输出路径
            mediaRecorder.setOutputFile(mCurrentFilePath);
            //设置声音来源 这个设置一定要在setOutputFormat()前调用,否则运行会报错
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    <span style="white-space:pre">	</span>//设置输出格式
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
    <span style="white-space:pre">	</span>//设置音频编码
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    
            try {
                mediaRecorder.prepare();
                mediaRecorder.start();
                isPrepare = true;
                if(onMediaRecorderPrepared != null)
                onMediaRecorderPrepared.prepared();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        
    
        public void release(){
            if(isPrepare){
                mediaRecorder.stop();
                mediaRecorder.release();
                mediaRecorder = null;
            }
        }
    
        public void cancle(){
            release();
            if(mCurrentFilePath != null){
                File file = new File(mCurrentFilePath);
                if(file.exists()){
                    file.delete();
                }
                mCurrentFilePath = null;
            }
        }
    
        public String getCurrentFilePath(){
            return mCurrentFilePath;
        }
    
        private String generateFile() {
            return UUID.randomUUID().toString() + ".amr";
        }
    }


    展开全文
  • 这是在Windows Phone 8.1中录制音频的基本方法指南
  • java同时录制音频视频

    2017-10-30 15:12:11
    自己编写的基于MFC框架的同时录制音频视频的java项目程序,一键控制同时录制并同时自动保存录制文件,自己编写,绝对可用,需要在工程里导MFC包
  • 我想以AMR文件格式录制音频.我目前正在使用波纹管代码来录制音频:outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "Sample.3gp";myRecorder = new MediaRecorder();myRecorder....
  • 使用Qt录制音频

    2018-11-04 15:39:02
    本片文章简单介绍一下使用Qt录制音频数据。 使用到的类为QAudioInput,使用这个类录制音频非常简单,基本步骤如下: 设置录制音频的采样率、大小和通道等信息,创建QAudioInput类的对象。 调用QAudioInput类的成员...
  • android 开发录制音频并播放demo
  • directshow 录制音频 faac编码
  • 音频(2)录制音频

    2019-10-03 19:38:03
    录制音频主要api  MediaRecorder.setAudioSource  MediaRecorder.setOutputFormat  MediaRecorder.setAudioEncoder  MediaRecorder.setOutputFile  MediaRecorder.prepare  MediaRecorder.start  ...
  • android用MediaRecoder录制音频,生成MP3文件
  • ppt录制音频及板书

    千次阅读 2020-07-31 21:57:06
    ppt录制音频及板书
  • ZYSoundViewController 录制音频,播放音频,转mp3格式,清理缓存 ##简陋效果图------核心功能有##
  • potplay播放器录制音频

    2020-01-12 21:45:52
    右键 | 声音 | 音轨 | 声音录制,(或者直接快捷键 shift+g) 打开录制音频界面。 随便选个格式,点击录制即可。这里选mp3,如图:
  • Android录制音频示例

    2017-08-26 11:23:02
    Android录制音频示例
  • medalRecorder录制音频

    2016-12-17 16:47:28
    medalRecorder录制音频
  • 这是在Windows Phone 8.1中录制音频的基本方法指南
  • AVAudioRecorder 录制音频

    2016-06-27 10:41:00
    AVFoundation 中使用AVAudioRecorder 类添加音频录制功能是非常简单的,... 我们可以在Mac机器和iOS设备上使用这个类来从内置的麦克风录制音频,也可以从外部音频设备进行录制(如耳塞) 项目代...
  • 本demo实现的是Android中利用AudioRecord实时录制音频转化为MP3格式的音频的实例,可以实现录制的开始、暂停、停止等功能。
  • ios应用源码之录制音频 demo recording .
  • 手机一般都提供了麦克风硬件,而Android系统就可以利用该硬件来录制音频了。 为了在Android应用中录制音频,Android提供了MediaRecorder类,使用MediaRecorder录制音频的过程如下: 1、创建MediaRecorder对象。 2...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 6,779
精华内容 2,711
关键字:

录制音频