簡體   English   中英

音頻播放器可在模擬器中工作,但不能在iOS設備上工作

[英]Audio player works in simulator but not on iOS device

我有以下代碼初始化:

NSString *path = [NSString stringWithFormat:@"%@/test.mp3", [[NSBundle mainBundle] resourcePath]];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];

然后一個按鈕啟動播放器

[_audioPlayer play];

因此,當我在模擬器上時,它工作正常,但在我的設備上不起作用。

在您的應用包中獲取文件路徑的正確方法如下:

NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp3"];

但是,如果您實際上想要一個NSURL ,請使用以下代碼直接獲取它:

NSURL *soundUrl = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"mp3"];

而且,模擬器不區分大小寫,但實際設備卻區分大小寫。 確保您的文件的名稱真實為test.mp3而不是Test.mp3類的Test.mp3 更新代碼中的名稱以匹配實際的文件名。

使用調試器確保soundURL不為nil 如果不是,但是音頻播放器仍然無法工作,請使用error參數查看原因:

NSError *error = nil;
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&error];
if (!_audioPlayer) {
    NSLog(@"Unable to create audio player: %@", error);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM