如何同时播放多个audio文件

如何在同一时间播放数字audio文件使用AVAudioPlayer? 是否可以播放audio文件可以使用AVAudioPlayer同时播放? 或者以任何其他方式同时播放多个audio文件? 谢谢!

具有以下格式的文件可以在iPhone上同时播放。

AAC,MP3和ALAC(Apple Lossless)audio:有CPU资源问题。 线性PCM和IMA / ADPCM(IMA4audio):无CPU资源问题。

您只需要为每个音乐文件创build一个新的播放器实例,即可播放。

示例代码片段:

-(void)playSounds{ [self playSound1]; [self playSound2]; } -(void)playSound1{ NSString *path = [[NSBundle mainBundle] pathForResource:@"file1" ofType:@"m4a"]; AVAudioPlayer* player= [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:path] error:NULL]; player.delegate = self; [player play]; } -(void)playSound2{ SString *path = [[NSBundle mainBundle] pathForResource:@"file2" ofType:@"m4a"]; AVAudioPlayer* player= [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:path] error:NULL]; player.delegate = self; [player play]; } 

转换为支持的格式(即MP3到咖啡):

/ usr / bin / afconvert -f caff -d ima4 sound.mp3 sound.caf

详细教程:

https://brainwashinc.wordpress.com/2009/08/14/iphone-playing-2-sounds-at-once/

Swift 2+解决scheme

– >现在你可以用mp3m4a后缀同时播放多个声音。 但是,如果你想将mp3转换为m4a,你可以从官方网站下载这个免费的程序: http : //audacityteam.org/download/mac/

你也可能需要FFmpeg 2+转换进程: http : //lame.buanzo.org/#lameosxdl

– >我更喜欢使用m4a,因为简而言之就是苹果自己的audio格式。

 //import AVFoundation // you have to define them first var player1 = AVAudioPlayer() var player2 = AVAudioPlayer() func playMultipleSound() { playSound1() playSound2() } func playSound1() { let soundUrl = NSBundle.mainBundle().URLForResource("sound1", withExtension: "mp3")! // or m4a do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) try AVAudioSession.sharedInstance().setActive(true) player1 = try AVAudioPlayer(contentsOfURL: soundUrl) player1.numberOfLoops = 0 player1.prepareToPlay() player1.play() } catch _ { return print("sound file not found") } } func playSound2() { let soundUrl = NSBundle.mainBundle().URLForResource("sound2", withExtension: "m4a")! // or mp3 do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) try AVAudioSession.sharedInstance().setActive(true) player2 = try AVAudioPlayer(contentsOfURL: soundUrl) player2.numberOfLoops = 0 player2.prepareToPlay() player2.play() } catch _ { return print("sound file not found") } } 

MPEG-4第14部分文件的唯一官方文件扩展名是.mp4,但是许多文件扩展名是.m4a和.m4p。 M4A(仅audio)通常使用AAC编码(有损)进行压缩,但也可以采用Apple Lossless格式。

Interesting Posts