gpt4 book ai didi

ios - AVFoundation-iOS听不到声音

转载 作者:行者123 更新时间:2023-12-03 02:21:12 27 4
gpt4 key购买 nike

我正在尝试使用AVFoundation框架播放mp3文件。它无法检测到文件,并出现以下错误:

     Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'

实现的代码:
NSString *path = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"];
NSLog(@"directory %@",path);
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];

当我将pathForResource:@“sound”更改为pathForResource:@“sound”(空格)时,它可以检测到文件,但听不到声音。我也在.h文件中声明了AVdelegate。有人知道出什么问题吗?

最佳答案

您需要先准备prepareToPlay才能播放音频。.检查此代码段..它对我有用。

NSArray *路径= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3", fileName]];

NSError *err;

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:filePath] error:&err];

player.delegate = self;

[player prepareToPlay];
[player setNumberOfLoops:0];
[player setVolume:0.5];
[player play];

}

关于ios - AVFoundation-iOS听不到声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12498293/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com