【发布时间】:2015-04-02 16:39:31
【问题描述】:
如何使用 AVAudioPlayer 同时播放多个音频文件? 是否可以使用 AVAudioPlayer 同时播放多个音频文件? 或任何其他方式同时播放多个音频文件? 谢谢!
【问题讨论】:
标签: ios multimedia
如何使用 AVAudioPlayer 同时播放多个音频文件? 是否可以使用 AVAudioPlayer 同时播放多个音频文件? 或任何其他方式同时播放多个音频文件? 谢谢!
【问题讨论】:
标签: ios multimedia
以下格式的文件可以在 iPhone 上同时播放。
AAC、MP3 和 ALAC(Apple 无损)音频:存在 CPU 资源问题。 线性 PCM 和 IMA/ADPCM(IMA4 音频):没有 CPU 资源问题。
您只需为要播放的每个音乐文件创建一个新的播放器实例。
示例代码 sn-p:
-(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 到 caf):
/usr/bin/afconvert -f caff -d ima4 sound.mp3 sound.caf
详细教程:
https://brainwashinc.wordpress.com/2009/08/14/iphone-playing-2-sounds-at-once/
【讨论】:
play(atTime:) 方法,用于定时同步启动多个音频文件。
Swift 2+解决方案
-> 现在您可以mp3 或m4a 后缀同时 播放多种声音。但是,如果您想将 mp3 转换为 m4a,您可以从官方网站下载这个免费程序: http://audacityteam.org/download/mac/
您可能还需要 FFmpeg 2+ 来转换过程: http://lame.buanzo.org/#lameosxdl
-> 我更喜欢使用 m4a 因为,总之它是 Apple 自己的音频格式。
//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 Part 14 文件的唯一官方文件扩展名是 .mp4, 但许多还有其他扩展名,最常见的是 .m4a 和 .m4p。 M4A (仅限音频)通常使用 AAC 编码(有损)进行压缩,但可以 也是 Apple 无损格式。
【讨论】: