[英]AVPlayer does not play file recorded with AVAudioRecorder — Swift
[英]How to name recorded file from AVAudioRecorder
我正在制作一個iOS應用,需要在其中使用AVAudioRecorder錄制語音,然后想重命名該文件。 現在,我可以成功錄制語音了,但是我不知道如何給文件指定自定義名稱。 如何給錄制的文件自定義名稱? 任何幫助表示贊賞。
在viewDidLoad
:
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
@"MyAudioMemo.m4a",
nil];
outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
// Setup audio session
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
// Initiate and prepare the recorder
recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:nil];
recorder.delegate = self;
recorder.meteringEnabled = YES;
[recorder prepareToRecord];
以及所有其他方法:
- (IBAction)recordPressed:(id)sender {
if (!recorder.recording) {
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
// Start recording
[recorder record];
NSLog(@"Recording...");
} else {
// Pause recording
[recorder pause];
NSLog(@"Paused...");
}
}
- (IBAction)stopPressed:(id)sender {
[recorder stop];
NSLog(@"Stopped...");
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setActive:NO error:nil];
}
您可以簡單地將文件移動到另一個路徑,這樣做時,可以為文件指定一個新名稱,這與shell中mv
命令的行為完全相同。
有一個非常簡單的代碼段可以幫助您了解如何使用FileManager moveItemAtPath:toPath:error
方法移動文件來重命名文件:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *newPath = [docsDir stringByAppendingPathComponent:@"newname.m4a"];
// Try to move your file and the current path to newPath
if ([fileManager moveItemAtPath:currentPath toPath:newPath error:&error] != YES)
{
NSLog(@"Error: %@", [error localizedDescription]);
}
else
{
// File moved success
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.