iOS的斯威夫特 - 合并和转换.wav文件为.mp3 [英] iOS Swift - Merge and convert .wav files to .mp3
问题描述
我要两个或多个.wav文件合并为一,然后将其转换为.mp3,这我想在做斯威夫特(或者至少有选项,它包括快速的项目)。
I want to merge two or more .wav files to one and then convert it to .mp3 and this I would like to done in Swift (or at least to have option to include it to swift project).
在合并迅疾2 .wav文件不是问题。 这里是我的例子现在的,我不知道该怎么瘸库添加到项目的迅速以及如何使用它(如何改变目标C瘸code使用语法来使用它SWIFT)。
Merge two .wav files in swift isn't problem. Here is my example Now I don't know how to add lame library to swift project and how to use it (how to change objective c lame code usage syntax to use it in swift).
我被困在SWIFT所以我尝试跛库,目的C.我发现例如code转换.caf为.mp3,所以我试了一下。以下是我已经试过:
I stuck in swift so I tried Lame library with Objective C. I found example code for converting .caf to .mp3 so I tried it. Here is what I've tried:
- (void) toMp3
{
NSString *cafFilePath = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"caf"];
NSString *mp3FileName = @"Mp3File";
mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];
NSString *mp3FilePath = [[NSHomeDirectory() stringByAppendingFormat:@"/Documents/"] stringByAppendingPathComponent:mp3FileName];
NSLog(@"%@", mp3FilePath);
@try {
int read, write;
FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb"); //source
fseek(pcm, 4*1024, SEEK_CUR); //skip file header
FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb"); //output
const int PCM_SIZE = 8192;
const int MP3_SIZE = 8192;
short int pcm_buffer[PCM_SIZE*2];
unsigned char mp3_buffer[MP3_SIZE];
lame_t lame = lame_init();
lame_set_in_samplerate(lame, 44100);
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
do {
read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
if (read == 0)
write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
else
write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
fwrite(mp3_buffer, write, 1, mp3);
} while (read != 0);
lame_close(lame);
fclose(mp3);
fclose(pcm);
}
@catch (NSException *exception) {
NSLog(@"%@",[exception description]);
}
@finally {
[self performSelectorOnMainThread:@selector(convertMp3Finish)
withObject:nil
waitUntilDone:YES];
}
}
- (void) convertMp3Finish
{
}
但是,这个结果只是噪声.MP3。
But result of this is just .mp3 with noise.
- Here is example .caf file.
- And here is result .mp3 file.
所以,我需要解决我的三个问题:
So I need fix my three problems:
- 从目标C CAF创建正确的MP3
- 更改code使用它的wav文件
- 并改变它能够在斯威夫特使用它
我知道有关于iOS的编码和转换MP3很多问题,但我不能找到一个与斯威夫特的例子,我不能工作目标C code找到例子(只需$以上C $ C) 。感谢您的帮助。
I know that there are many questions about encoding and converting mp3 in iOS but I can't find one with Swift example and I can't find example with working Objective C code (just code above). Thanks for help
推荐答案
我要发布我的工作解决方案,因为我得到这么多的竖起大拇指,并从纳雷什答案并不能帮助我很多。
I would like to post my working solution because I get so many thumbs up and answer from naresh doesn't help me much.
- 我产生lame.framework库 https://github.com/wuqiong/ mp3lame换的iOS
- 我添加库到我的雨燕项目(建设阶段 - >链接二进制库)
- 我创建的包装使用在Objective C C函数和由桥接报头我用它在斯威夫特。
- 对于我使用AVAssetExportSession与斯威夫特串连wav文件
从这个项目
而现在源$ C $ CS。所以先包装。它的类文件转换为.WAV .MP3。可能有很多的变化(也许参数输出文件和其他选项),但我想每个人都可以改变它。我想这可以改写斯威夫特,但我不知道该怎么做。所以这是目标C类:
And now source codes. So first wrapper. It's class for converting .wav files to .mp3. There could be many changes (maybe parameter for output file and other options) but I think everyone could change it. I guess this could be rewritten to Swift but I wasn't sure how to do it. So it's Objective C class:
#import "AudioWrapper.h"
#import "lame/lame.h"
@implementation AudioWrapper
+ (void)convertFromWavToMp3:(NSString *)filePath {
NSString *mp3FileName = @"Mp3File";
mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];
NSString *mp3FilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:mp3FileName];
NSLog(@"%@", mp3FilePath);
@try {
int read, write;
FILE *pcm = fopen([filePath cStringUsingEncoding:1], "rb"); //source
fseek(pcm, 4*1024, SEEK_CUR); //skip file header
FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb"); //output
const int PCM_SIZE = 8192;
const int MP3_SIZE = 8192;
short int pcm_buffer[PCM_SIZE*2];
unsigned char mp3_buffer[MP3_SIZE];
lame_t lame = lame_init();
lame_set_in_samplerate(lame, 44100);
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
do {
read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
if (read == 0)
write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
else
write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
fwrite(mp3_buffer, write, 1, mp3);
} while (read != 0);
lame_close(lame);
fclose(mp3);
fclose(pcm);
}
@catch (NSException *exception) {
NSLog(@"%@",[exception description]);
}
@finally {
[self performSelectorOnMainThread:@selector(convertMp3Finish)
withObject:nil
waitUntilDone:YES];
}
}
斯威夫特AudioHelper类concatening音频文件和调用方法的.wav文件转换为.MP3:
Swift AudioHelper class for concatening audio files and calling method for converting .wav file to .mp3:
import UIKit
import AVFoundation
protocol AudioHelperDelegate {
func assetExportSessionDidFinishExport(session: AVAssetExportSession, outputUrl: NSURL)
}
class AudioHelper: NSObject {
var delegate: AudioHelperDelegate?
func concatenate(audioUrls: [NSURL]) {
//Create AVMutableComposition Object.This object will hold our multiple AVMutableCompositionTrack.
var composition = AVMutableComposition()
var compositionAudioTrack:AVMutableCompositionTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
//create new file to receive data
var documentDirectoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as! NSURL
var fileDestinationUrl = NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingPathComponent("resultmerge.wav"))
println(fileDestinationUrl)
StorageManager.sharedInstance.deleteFileAtPath(NSTemporaryDirectory().stringByAppendingPathComponent("resultmerge.wav"))
var avAssets: [AVURLAsset] = []
var assetTracks: [AVAssetTrack] = []
var durations: [CMTime] = []
var timeRanges: [CMTimeRange] = []
var insertTime = kCMTimeZero
for audioUrl in audioUrls {
let avAsset = AVURLAsset(URL: audioUrl, options: nil)
avAssets.append(avAsset)
let assetTrack = avAsset.tracksWithMediaType(AVMediaTypeAudio)[0] as! AVAssetTrack
assetTracks.append(assetTrack)
let duration = assetTrack.timeRange.duration
durations.append(duration)
let timeRange = CMTimeRangeMake(kCMTimeZero, duration)
timeRanges.append(timeRange)
compositionAudioTrack.insertTimeRange(timeRange, ofTrack: assetTrack, atTime: insertTime, error: nil)
insertTime = CMTimeAdd(insertTime, duration)
}
//AVAssetExportPresetPassthrough => concatenation
var assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetPassthrough)
assetExport.outputFileType = AVFileTypeWAVE
assetExport.outputURL = fileDestinationUrl
assetExport.exportAsynchronouslyWithCompletionHandler({
self.delegate?.assetExportSessionDidFinishExport(assetExport, outputUrl: fileDestinationUrl!)
})
}
func exportTempWavAsMp3() {
let wavFilePath = NSTemporaryDirectory().stringByAppendingPathComponent("resultmerge.wav")
AudioWrapper.convertFromWavToMp3(wavFilePath)
}
}
衔接头包含:
#import "lame/lame.h"
#import "AudioWrapper.h"
这篇关于iOS的斯威夫特 - 合并和转换.wav文件为.mp3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!